1、场景里新建四个东西
新建Empty:Hierarchy面板下右击->Create Empty
2、Empty的位置是在diren的炮口处
3、制作子弹的预制体
4、diren挂上此代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class chatAI : MonoBehaviour { public GameObject Player; public float movementSpeed = 4; public GameObject bullet; public Transform bullstSpawn; float time = 0; void Start() { //_Agent = this.GetComponent<UnityEngine.AI.NavMeshAgent>(); } // Update is called once per frame void Update() { float x = Random.Range(0, 20); float z = Random.Range(-10, 10); while (x > 0) { this.transform.position += this.transform.forward * x * Time.deltaTime; this.transform.eulerAngles += new Vector3(0.0f, 30.0f, 0.0f) * z * Time.deltaTime; x -= 10; } movementSpeed = 1;//坦克速度 float dist = Vector3.Distance(Player.transform.position, transform.position);//坦克与小车之间的距离 if (dist < 20) { transform.LookAt(Player.transform);//坦克朝向小车 movementSpeed = 2;//车后的速度变4 time += Time.deltaTime;//计时 if (time > 2)//当坦克与车的距离小于20大于2s后 { Fire();//开火 time = 0;//时间重置 } } transform.position += transform.forward * movementSpeed * Time.deltaTime;//改变坦克位置 } void Fire() {//开火 GameObject bulletgo = Instantiate(bullet,bullstSpawn.position, bullstSpawn.rotation);//实例化子弹 bulletgo.GetComponent<Rigidbody>().velocity = transform.forward * 20.0f;//子弹运动 Destroy(bulletgo, 2);//两秒后消灭子弹 } }
Player----car(Hierarchy)
Bullst Spawn-----e(Hierarchy)
Bullet----bullet(Project)
5、car挂上此代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class carmove : MonoBehaviour { // Use this for initialization void Start () { //GetComponent<Rigidbody>().freezeRotation = true; } // Update is called once per frame void Update() { float y = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;//旋转角度,水平方向上的变换 float z = Input.GetAxis("Vertical") * Time.deltaTime * 10.0f;//控制前后 transform.Rotate(0, y, 0);//绕y轴旋转 transform.Translate(0, 0, z);//在水平方向上运动位置 } private void OnCollisionEnter(Collision coll) {//坦克的碰撞检测 if (coll.transform.tag == "diren") {//if (coll.transform.name == "diren") } } }
效果