Unity3D基础34.1:打砖块小游戏优化
前文:https://blog.****.net/Jaihk662/article/details/86768910(打砖块小游戏设计)
前面实现了一个非常的简单打砖块小游戏,但可以发现里面有许多不合理的地方(特性)
一、优化:当方块掉下去的时候,到达一定高度后销毁它
给方块添加脚本如下即可:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeDes : MonoBehaviour
{
private Transform myTran;
void Start()
{
myTran = gameObject.GetComponent<Transform>();
}
void Update()
{
if (myTran.position.y<=-10)
{
GameObject.Destroy(gameObject);
}
}
}
二、优化:当小球射出去8秒后,让它自动销毁
一样给小球添加脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereDes : MonoBehaviour
{
void Start()
{
GameObject.Destroy(gameObject, 8);
}
void Update()
{
}
}
三、修改:无论鼠标指向哪里,小球都能射出
其实代码多此一举了,根本就没有必要检测射线碰撞,所以需要稍微修改下代码
除此之外,还可以通过直接获取射线的方向,来确定射出小球时力的方向
Ray.direction.x/y/z:获取射线的方向
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeCreate : MonoBehaviour
{
private int x, y;
public GameObject myCube, mySph;
RaycastHit hit;
private Ray ray;
private Transform myTran;
void Start ()
{
CreateCube();
myTran = gameObject.GetComponent<Transform>();
}
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
Shot();
}
}
void Shot()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//if (Physics.Raycast(ray, out hit)) //没有必要
//{
GameObject go = GameObject.Instantiate(mySph, myTran.position, Quaternion.identity) as GameObject; //生成“子弹”
//Vector3 dir = hit.point - myTran.position;
go.GetComponent<Rigidbody>().AddForce(new Vector3(ray.direction.x, ray.direction.y, ray.direction.z) * 1360); //给予“子弹”一个力
//}
}
void CreateCube()
{
x = 10;
y = 5;
for (int i = 0; i <= x; i++)
{
for (int j = 0; j <= y; j++)
{
GameObject.Instantiate(myCube, new Vector3(i - 5, j + 0.5f, 0), Quaternion.identity);
}
}
}
}
最终修改后结果: