Unity3D 入门小技巧——鼠标拾取并移动物体
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3D 入门小技巧——鼠标拾取并移动物体相关的知识,希望对你有一定的参考价值。
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;
- // 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>
应用一:当鼠标按住不动时,移动被选定物体随鼠标一起移动
- <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>
应用二:当鼠标点击物体时,物体随鼠标一起移动;当鼠标再次点击时,放下物体。
- <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 入门小技巧——鼠标拾取并移动物体的主要内容,如果未能解决你的问题,请参考以下文章
Unity基于响应式编程(Reactive programming)入门