unity|敵方坦克自由移動,當靠近到一定距離后,可自動攻擊


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") } } } 

效果
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM