手把手教你写Unity3D飞机大战(6)玩家子弹射击之瞄准程序(射线检测)
一、射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, 10000f)) {Debug.Log("瞄准物体: " + hitInfo.transform.name); }
二、发射
我们可以通过射线检测来获取遇到的物体,也可以获取遇到物体的位置。
具体怎么做呢?
我的做法是从射线机往瞄准点打出射线,然后获取射线的碰撞点,再从两侧的发射点向瞄准点发射子弹。
if (Input.GetMouseButton(0) && Time.time - lastTime > 0.1f) {lastTime = Time.time; // 定时器,每秒最多10发GameObject p1 = GameObject.Find("Player/left"), p2 = GameObject.Find("Player/right");Create(p1.transform.position);Create(p2.transform.position); }
首先确定框架。
void Create(Vector3 p) {num++;if (num >= 100)num = 100; // 子弹总数tmp = (tmp + 1) % 100; // 一旦超过100发,循环利用,0会自动忽略GameObject old = GameObject.Find("Bullet"); // 找到原体GameObject nw = null; // 新建子弹if (old != null && num == 100)nw = GameObject.Find("Bullet" + tmp.ToString()); // 循环利用else if (old != null)nw = Instantiate(old); // 新建一个if (nw != null)nw.name = "Bullet" + tmp.ToString(); // 重新命名if (nw != null){// 射线检测Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit hitInfo;if (Physics.Raycast(ray, out hitInfo, 10000f)){nw.transform.position = p; // 确定发射位置nw.transform.LookAt(hitInfo.point); // 确定子弹朝向}} }
Create负责创造子弹。
for (int i = 1; i <= num; i++) {GameObject th = GameObject.Find("Bullet" + i.ToString());if (th != null){th.transform.Translate(0, 0, 2.5f);} }
子弹的移动。
三、子弹的基础
我们必须有一个原体子弹,这样才能克隆出来。
我把它藏在机场内部,反正不要让玩家看到就好。
四、源码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements;public class Shoot : MonoBehaviour {public int num = 0, tmp = 0;private float lastTime;void Start(){lastTime = Time.time;}void Create(Vector3 p){num++;if (num >= 100)num = 100;tmp = (tmp + 1) % 100;GameObject old = GameObject.Find("Bullet");GameObject nw = null;if (old != null && num == 100)nw = GameObject.Find("Bullet" + tmp.ToString());else if (old != null)nw = Instantiate(old);if (nw != null)nw.name = "Bullet" + tmp.ToString();if (nw != null){Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);RaycastHit hitInfo;if (Physics.Raycast(ray, out hitInfo, 10000f)){nw.transform.position = p;nw.transform.LookAt(hitInfo.point);}}}void FixedUpdate(){if (Input.GetMouseButton(0) && Time.time - lastTime > 0.1f){lastTime = Time.time;GameObject p1 = GameObject.Find("Player/left"), p2 = GameObject.Find("Player/right");Create(p1.transform.position);Create(p2.transform.position);}for (int i = 1; i <= num; i++){GameObject th = GameObject.Find("Bullet" + i.ToString());if (th != null){th.transform.Translate(0, 0, 2.5f);}}} }
本篇文章有点复杂,如果没有看懂,欢迎留言。