unity讓物體移動到滑鼠點選點
阿新 • • 發佈:2019-02-04
using UnityEngine; using System.Collections; public class test : MonoBehaviour { //在場景中滑鼠點選地面後,角色可以移動到目標位置 private Vector3 target; private bool isOver = true; public float speed; void Start () { } void Update () { if(Input.GetMouseButtonDown(0)) { print("MouseDown"); //1. 獲取滑鼠點選位置 //建立射線;從攝像機發射一條經過滑鼠當前位置的射線 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //發射射線 RaycastHit hitInfo = new RaycastHit(); if (Physics.Raycast(ray, out hitInfo)) { //獲取碰撞點的位置if (hitInfo.collider.name == "Plane") { target = hitInfo.point; target.y += 0.5f; isOver = false; } } //RaycastHit[] hitAll = Physics.RaycastAll(ray, 1000); //foreach(RaycastHit hitInfo in hitAll)//{ // print(hitInfo.collider.name); // if (hitInfo.collider.name == "Plane") // { // target = hitInfo.point; // target.y = 0.5f; // isOver = false; // } //} } //2. 讓角色移動到目標位置 MoveTo(target); } //讓角色移動到目標位置 private void MoveTo(Vector3 tar) { if(!isOver) { Vector3 offSet = tar - transform.position; transform.position += offSet.normalized * speed * Time.deltaTime; if(Vector3.Distance(tar, transform.position)<0.5f) { isOver = true; transform.position = tar; } } } }