首页 > 代码库 > 【转】Unity3D 入门小技巧——鼠标拾取并移动物体
【转】Unity3D 入门小技巧——鼠标拾取并移动物体
http://blog.csdn.net/sysujackjiao/article/details/69396274
一、鼠标拾取物体的原理
在Unity3D当中,想要在观察面(Aspect)中拾取物体(有碰撞属性)的方法一般如下:
1、声明一个观察的摄像机、一个从摄像机原点出发的射线Ray以及一个用于检测碰撞的RaycastHit;
2、将射线Ray定义为从摄像机原点出发并且指向当前鼠标所在的坐标(屏幕坐标);
3、定义碰撞RaycastHit为射线Ray与有碰撞属性的物体的碰撞点。
具体代码实现如下(C#代码):
[csharp] view plain copy
- <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;
- // Use this for initialization
- void Start()
- {
- }
- // Update is called once per frame
- void Update()
- {
- ra = ca.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ra, out hit))
- {
- }
- }
- }</span>
应用一:当鼠标按住不动时,移动被选定物体随鼠标一起移动
[csharp] view plain copy
- <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;
- // Use this for initialization
- void Start()
- {
- }
- // Update is called once per frame
- 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>
应用二:当鼠标点击物体时,物体随鼠标一起移动;当鼠标再次点击时,放下物体。
[csharp] view plain copy
- <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;
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- 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>
Unity3D鼠标坐标转世界坐标和局部坐标
鼠标坐标转世界坐标和局部坐标:
Vector3 MousePosition2Local () {
mousePosition = Input.mousePosition; //获取屏幕坐标
mouseWorldPos = Camera.main.ScreenToWorldPoint (mousePosition); //屏幕坐标转世界坐标
mouseLocalPos = transform.parent.transform.InverseTransformPoint (mouseWorldPos); //世界坐标转本地坐标
return CorrectPos(mouseLocalPos);
}
【转】Unity3D 入门小技巧——鼠标拾取并移动物体
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。