unity项目:坦克大战:自己的坦克代码
·
将代码添加到要控制的坦克身上,添加刚体、碰撞体

public class TankMove : MonoBehaviour
{
[Header("炮弹的预设体")]
public GameObject bulletPrefab;
[Header("移动速度")]
public float moveSpeed = 1;
[Header("转身速度")]
public float turnSpeed = 1f;
[Header("敌人预设体")]
public GameObject tankPrefab;
public float emptyShuaXinTime = 5f;
//炮弹发射点对象的Transform
private Transform firePoint;
float hor, ver;
bool fire;
private void Awake()
{
//找到炮弹发射点
firePoint = transform.Find("FirePoint");
}
private void Update()
{
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical");
fire = Input.GetButtonDown("Fire");
//前后移动
transform.position +=
transform.right * ver
* moveSpeed;
//左右转身
transform.eulerAngles +=
Vector3.up * hor * turnSpeed;
if (fire)
{
//生成炮弹
GameObject blt = Instantiate(
bulletPrefab,
firePoint.position,
Quaternion.identity);
//让子弹飞
blt.GetComponent<Bullet>().moveDir = transform.right;
//3s后销毁
Destroy(blt, 3f);
}
emptyShuaXinTime -= Time.deltaTime; //生成敌人
if (emptyShuaXinTime < 0)
{
GameObject empty = Instantiate(tankPrefab);
Vector3 weiZhi = new Vector3(Random.Range(0, 500), 0, Random.Range(0, 500));
while ((weiZhi - transform.position).sqrMagnitude < 400f)
{
weiZhi = new Vector3(Random.Range(0, 500), 0, Random.Range(0, 500));
}
empty.transform.position = new Vector3(Random.Range(0, 500), 0, Random.Range(0, 500));
empty.transform.Rotate(new Vector3(0, Random.Range(0, 360), 0));
emptyShuaXinTime = 3f;
empty.transform.position += new Vector3(1,0,0);
}
}
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.gameObject.tag == "paoDan")
{
Debug.Log("GameOver");
}
}
}
更多推荐



所有评论(0)