标签:sdn detail mono font tail put 屏幕 获取 image
http://blog.csdn.net/sysujackjiao/article/details/69396274
一、鼠标拾取物体的原理
在Unity3D当中,想要在观察面(Aspect)中拾取物体(有碰撞属性)的方法一般如下:
1、声明一个观察的摄像机、一个从摄像机原点出发的射线Ray以及一个用于检测碰撞的RaycastHit;
2、将射线Ray定义为从摄像机原点出发并且指向当前鼠标所在的坐标(屏幕坐标);
3、定义碰撞RaycastHit为射线Ray与有碰撞属性的物体的碰撞点。
具体代码实现如下(C#代码):
- <span style="font-size:10px;">using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class camera : MonoBehaviour
- {
- public Camera ca;
- private Ray ra;
- private RaycastHit hit;
-
-
- void Start()
- {
-
- }
-
-
- void Update()
- {
- ra = ca.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ra, out hit))
- {
-
- }
- }
- }</span>
应用一:当鼠标按住不动时,移动被选定物体随鼠标一起移动
- <span style="font-size:10px;">using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class camera : MonoBehaviour
- {
- public Camera ca;
- private Ray ra;
- private RaycastHit hit;
-
-
- void Start()
- {
-
- }
-
-
- void Update()
- {
- if (Input.GetMouseButton(0))
- {
- ra = ca.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ra, out hit))
- {
- hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
- }
- }
- }
- }</span>
应用二:当鼠标点击物体时,物体随鼠标一起移动;当鼠标再次点击时,放下物体。
- <span style="font-size:12px;">using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class camera : MonoBehaviour {
- public Camera ca;
- private Ray ra;
- private RaycastHit hit;
- private int flag = 0;
-
-
- void Start () {
-
- }
-
-
- void Update () {
- if (Input.GetMouseButtonDown(0))
- {
- ra = ca.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ra, out hit))
- {
- if (flag == 0)
- {
- flag = 1;
- } else
- {
- flag = 0;
- }
- }
- }
- if (flag == 1)
- {
- hit.collider.gameObject.transform.position = ca.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.collider.gameObject.transform.position.z));
- }
-
- }
- }
- </span>
鼠标坐标转世界坐标和局部坐标:
Vector3 MousePosition2Local () {
mousePosition = Input.mousePosition; //获取屏幕坐标
mouseWorldPos = Camera.main.ScreenToWorldPoint (mousePosition); //屏幕坐标转世界坐标
mouseLocalPos = transform.parent.transform.InverseTransformPoint (mouseWorldPos); //世界坐标转本地坐标
return CorrectPos(mouseLocalPos);
}
【转】Unity3D 入门小技巧——鼠标拾取并移动物体
标签:sdn detail mono font tail put 屏幕 获取 image
原文地址:http://www.cnblogs.com/mimime/p/6757467.html