①利用射线和自动寻路实现在小地图中点击场景中物体实现目标移动
代码:
public class MapCameraRayTest : MonoBehaviour
{
[SerializeField]
private Camera mapCamera;
private RaycastHit hit;
private NavMeshAgent agent;
private void Start ()
{
agent = GetComponent<NavMeshAgent> ();
}
private void Update ()
{
Ray ray = mapCamera.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray,out hit,100) && Tag.Hourse == hit.transform.tag && Input.GetMouseButton(0))
{
Debug.DrawLine (mapCamera.transform.position,hit.point,Color.red);
agent.SetDestination (hit.transform.position);
}
}
}
②利用射线实现拾取物体:
public class Pickup : MonoBehaviour
{
[SerializeField]
private Transform handlerTF;
private RaycastHit hit;
private Transform carryTF;
private bool isPickup;
[SerializeField]
private Transform uiPoint;
private void Update () {
if (Physics.Raycast (handlerTF.position, handlerTF.forward, out hit, 2) &&
Tag.Hourse == hit.transform.tag)
{
uiPoint.gameObject.SetActive (true);
uiPoint.position = Camera.main.WorldToScreenPoint (hit.point);
if (!isPickup)
carryTF = hit.transform;
}
else
uiPoint.gameObject.SetActive (false);
if (null == carryTF) return;
if (Input.GetMouseButton(0)) {
carryTF.parent = handlerTF;
carryTF.localPosition = new Vector3(0,0,1);
carryTF.localEulerAngles = Vector3.zero;
isPickup = true;
}
else
{
isPickup = false;
carryTF.parent = null;
carryTF.localEulerAngles = new Vector3 (0, carryTF.localEulerAngles.y, 0);
carryTF = null;
}
}
}
③发射激光线:
public class Shoot : MonoBehaviour
{
[SerializeField]
private Transform uiPoint;
private RaycastHit hit;
private LineRenderer linearRenderer;
private void Start ()
{
linearRenderer = GetComponent<LineRenderer> ();
}
private void Update () {
if (Physics.Raycast (this.transform.position, this.transform.forward, out hit, 100)
&& Input.GetMouseButton(0) )
{
uiPoint.gameObject.SetActive (true);
uiPoint.position = Camera.main.WorldToScreenPoint(hit.point);
linearRenderer.enabled = true;
linearRenderer.SetPosition(0,this.transform.position);
linearRenderer.SetPosition (1,this.hit.point);
}
else
{
uiPoint.gameObject.SetActive (false);
linearRenderer.enabled = false;
}
}
}