参考:unity5实战第三章,慢慢学习
放两个东西
一个是玩家,主摄像机附在上面,配上Mouselook.cs,FPSInput.cs使其能响应键盘移动跟鼠标移动
Mouselook.cs,FPSInput.cs的实现前面有
一个是敌人,附上Reactive.cs受击反馈脚本,实现在下面
现在要做的是:按下左键,射出子弹,被射中区域显示球(子弹),被射中的敌人受击反馈消失
现在给玩家的主摄像机配上rayshoot.cs ,摄像机可以射出射线。
rayshoot.cs编写思路:
0.OnGUI()写个准星
1.响应左键,使用carema的API在摄像机位置产生射线
2.如果射中了(不一定是敌人)
A.射中敌人,命令敌人调用受击反馈函数,敌人1s后消失
B.射中别的,产生(子弹)小球附上射中的点上,子弹1s后消失
由于需要延时消失,用协程来实现
实现如下
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class RayShooter : MonoBehaviour { private Camera _camera; // Use this for initialization void Start () { _camera = GetComponent<Camera>(); } void OnGUI() { int size = 12; float posX = _camera.pixelWidth / 2 - size / 4; float posY = _camera.pixelHeight / 2 - size / 2; GUI.Label(new Rect(posX, posY, size, size), "*"); } // Update is called once per frame void Update () { //响应左键 if (Input.GetMouseButton(0)==true) { Vector3 point = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight/2, 0); Ray ray=_camera.ScreenPointToRay(point); RaycastHit hit; if (Physics.Raycast(ray, out hit))//hit就是被击中的目标 { // Debug.Log(point); //获取打到的物体 GameObject hitobj = hit.transform.gameObject; ReactiveTarget RT = hitobj.GetComponent<ReactiveTarget>(); if (RT != null){ RT.Reacttohit();//调用敌人的被击反馈 } else{ StartCoroutine(F(hit.point));//用协程造子弹,因为要编写子弹要1s后消失的效果 } } } } private IEnumerator F(Vector3 pos)//协程 { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.transform.position = pos; yield return new WaitForSeconds(1); Destroy(sphere);//1s后消失 } }
敌人需要受击反馈,1.5s后消失,使用协程,ReactiveTarget.cs如下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveTarget : MonoBehaviour { public void Reacttohit() { StartCoroutine(Die()); } private IEnumerator Die() { this.transform.Rotate(-75, 0, 0); yield return new WaitForSeconds(1.5f); Destroy(this.gameObject); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }