unity3d射线控制移动
2015-06-29 20:57 糯米粥 阅读(1506) 评论(0) 编辑 收藏 举报看看效果图
代码:
1 using UnityEngine; 2 using System.Collections; 3 4 public class T2 : MonoBehaviour 5 { 6 7 // Use this for initialization 8 void Start() 9 { 10 11 } 12 13 //定义射线 14 Ray ray; 15 RaycastHit hit; 16 //是否移动 17 bool isMove; 18 //移动方向 19 Vector3 dir; 20 Vector3 pos; 21 22 // Update is called once per frame 23 void Update() 24 { 25 //float v = Input.GetAxis("Vertical"); 26 //float h = Input.GetAxis("Horizontal"); 27 //transform.Translate(transform.forward * v * Time.deltaTime); 28 29 30 //transform.Rotate(Vector3.up * h); 31 32 33 //鼠标左键按下的时候 34 if (Input.GetMouseButtonDown(0)) 35 { 36 //从摄像机发一条射线 37 ray = Camera.main.ScreenPointToRay(Input.mousePosition); ; 38 //如果检测到物体(射线用来检测) 39 if (Physics.Raycast(ray, out hit)) 40 { 41 //将碰撞点的Y值变为transform的Y值 42 pos = new Vector3(hit.point.x, transform.position.y, hit.point.z); 43 44 45 //hit.point是物体的位置 46 transform.LookAt(hit.point); 47 //开始移动 48 isMove = true; 49 //求移动方向 50 //dir = (hit.point - transform.position).normalized; 51 52 dir = (pos - transform.position).normalized; 53 54 } 55 } 56 //如果开始移动 57 if (isMove) 58 { 59 //沿着世界坐标的某一个位置移动 60 transform.Translate(dir * Time.deltaTime * 3, Space.World); 61 //如果距离小于0.5m的时候,停止移动 62 if (Vector3.Distance(transform.position, hit.point) < 0.5f) 63 { 64 isMove = false; 65 } 66 } 67 68 69 70 } 71 }
当然。出来用LookAt还可以用LookRotation
using UnityEngine; using System.Collections; //加刚体 public class movee : MonoBehaviour { // Use this for initialization void Start() { } bool isMove; Vector3 dir; RaycastHit hit; Vector3 hitPoint; Quaternion rotation; Quaternion originRatation; float timer; // Update is called once per frame void FixedUpdate() { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { hitPoint = new Vector3(hit.point.x, transform.position.y, hit.point.z); //transform.LookAt(hit.point); //dir = (hit.point - transform.position).normalized; dir = hitPoint - transform.position; rotation = Quaternion.LookRotation(dir); originRatation = transform.rotation; isMove = true; timer = 0; } } if (isMove) { //transform.Translate(dir * Time.deltaTime * 5, Space.World); timer += Time.fixedDeltaTime; //if (Vector3.Distance(transform.position, hit.point) < 0.5) isMove = false; //慢慢旋转过去,这不是匀速的。 //transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.fixedDeltaTime*5); //既然想匀速的话,那么起点和终点不变。时间变化 transform.rotation = Quaternion.Lerp(originRatation, rotation, timer); //transform.rotation = rotation; //角度直接等于这个 if (Quaternion.Angle(transform.rotation, rotation) < 2) { transform.rotation = rotation; isMove = false; } } } public void Update() { } }