//画出当前射线
1 |
Debug.DrawRay(tempVec,transform.forward, Color.green, 2f); |
通过二进制转换选中层 (射线,射线碰到的物体信息,距离,层)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//定义射线接收鼠标的坐标 Ray r = Camera.main.ScreenPointToRay (Input.mousePosition); if (Input.GetMouseButtonDown (0)) { RaycastHit rc; int cubeIndex = LayerMask.NameToLayer ("Cube"); int sphereIndex = LayerMask.NameToLayer ("Sphere"); //r为鼠标位置和方向 rc为存储投射到的物体信息, 100f为投射距离, 1<<layerIndex 为cube所在层 //1<<layerIndex 为将1向前推layerIndex位,转换为二进制 //1 << cubeIndex | 1 << sphereIndex) 将cubeIndex和sphereIndex同时补1,转为二进制 if (Physics.Raycast (r,out rc, 100f, 1 << cubeIndex | 1 << sphereIndex)) { Destroy (rc.transform.gameObject); } } |
通过外界层掩码变量选中层 (射线,射线碰到的物体信息,距离,层)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//定义层掩码公共变量 用于接收选中为哪几个层 public LayerMask lm; // Update is called once per frame void Update () { //定义射线接收鼠标的坐标 Ray r = Camera.main.ScreenPointToRay (Input.mousePosition); if (Input.GetMouseButtonDown (0)) { RaycastHit rc; int cubeIndex = LayerMask.NameToLayer ("Cube"); int sphereIndex = LayerMask.NameToLayer ("Sphere"); //r为鼠标位置和方向 rc为存储投射到的物体信息, 100f为投射距离, lm选中的层 if (Physics.Raycast (r,out rc, 100f, lm)) { Destroy (rc.transform.gameObject); rc.point; //获取rc坐标 } } } |
使物体跟随鼠标点击位置行驶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
GameObject g; bool isMove; bool isMoveOver; Vector3 vec; Vector3 vec2; // Use this for initialization void Start () { g = GameObject.Find ("Player"); isMove = false; } // Update is called once per frame void Update () { MoveTo (); isMoving (); } //鼠标点击,并判断点击位置是否为地面 void MoveTo () { if (Input.GetMouseButton (0)) { Ray r = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit rc = new RaycastHit (); if (Physics.Raycast (r,out rc)) { if (rc.transform.gameObject.tag == "plane") { isMove = true; vec = rc.point; } } } } //通过Mathf.Lerp来变速移动 void isMoving () { if (isMove) { float x=Mathf.Lerp(g.transform.position.x,vec.x,Time.deltaTime * 2); float z=Mathf.Lerp(g.transform.position.z,vec.z,Time.deltaTime * 2); g.transform.position = new Vector3 (x,g.transform.position.y,z); // isMoveOver = true; if (g.transform.position == vec) { isMove = false; } } } |
- 本文固定链接: http://www.u3d8.com/?p=210
- 转载请注明: 网虫虫 在 u3d8.com 发表过