Unity3D拖动任意对象GameObject移动到任意地方
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3D拖动任意对象GameObject移动到任意地方相关的知识,希望对你有一定的参考价值。
今天不是很忙,研究了一下拖拽GameObject移动到任意位置,沿x轴和z轴移动,其他的也就不说了,上代码:
using UnityEngine; using System.Collections; public class DragAndDrog : MonoBehaviour { private GameObject target; private bool isMouseDrag; private Vector3 screenPosition; private Vector3 offset; // Use this for initialization void Start () { } // Update is called once per frame void Update () { GameObjectDragAndDrog(); } //任意拖拽 private GameObject ReturnGameObjectDrag(out RaycastHit hit) { target = null; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray.origin, ray.direction * 10, out hit)) { target = hit.collider.gameObject; } return target; } //拖拽Updata private void GameObjectDragAndDrog() { if (Input.GetMouseButtonDown (0)) { RaycastHit hitInfo; target = ReturnGameObjectDrag(out hitInfo); if (target != null) { isMouseDrag = true; screenPosition = Camera.main.WorldToScreenPoint(target.transform.position); offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z)); } } if (Input.GetMouseButtonUp(0)) { isMouseDrag = false; } if (isMouseDrag) { Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z); Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset; target.transform.localPosition = new Vector3(currentPosition.x, currentPosition.y, currentPosition.z); } } } 本脚本可以加载任意一个对象GameObject,场景中所有带Collider的对象,当鼠标点击拖动时候都可以沿x和z轴拖动。之前,都是要拖动那个GameObject就会写一个脚本挂在上面,今天实现了不用每一个要拖动的GameObject都挂载脚本,也不用将移动的GameObject赋给某个变量。
本文出自 “Unity_3D技术探讨” 博客,请务必保留此出处http://caoliyong.blog.51cto.com/9944020/1740192
以上是关于Unity3D拖动任意对象GameObject移动到任意地方的主要内容,如果未能解决你的问题,请参考以下文章
[Unity3D] GameObject and MonoBehaviour
Unity3d关于Gameobject ,gameObject,Transform,transform的区别和关联的一些个人理解