游戏中的激光射线很是有趣,来看看unity中如何实现吧。
首先添加lineRender组件,设置lineRender为false,初始状态不可见,然后选择合适Materials

下面定义代码PlayerShooter.cs:
public float range = 100f;//射击范围 public float timeBetweenBullets = 0.15f;//发射子弹的间隔 float effectsDisplayTime = 0.2f;//子弹消失的时间 float timer;//计时器 Ray shootRay; //定义射线 RaycastHit shootHit; LineRenderer gunLine; int shootableMask;//定义接受射线的面,mask
获取组件
void Awake() { shootableMask = LayerMask.GetMask("Shootable"); gunLine = GetComponent<LineRenderer>(); }
update里面的逻辑
void Update () { timer += Time.deltaTime; if (Input.GetButton("Fire1") && timer >= timeBetweenBullets) { Debug.Log("timer,timeBetweenBullets:" + timer + "," + timeBetweenBullets); Shoot(); } if (timer >= timeBetweenBullets * effectsDisplayTime) { DisableEffects(); } }
//效果消失
public void DisableEffects() { gunLine.enabled = false; }
射击函数,此函数主要处理射线射中物体的逻辑
void Shoot() { timer = 0f; gunLine.enabled = true; //gunLine.SetPosition(0, transform.position); shootRay.origin = transform.position; shootRay.direction = transform.forward; // Perform the raycast against gameobjects on the shootable layer and if it hits something... if (Physics.Raycast(shootRay, out shootHit, range, shootableMask)) { //击中,do something // Set the second position of the line renderer to the point the raycast hit. gunLine.SetPosition(1, shootHit.point); } else { gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range); } }
浙公网安备 33010602011771号