我正在寻找 Unity 2D 的对象拖动脚本。我在网上找到了一个很好的方法,但它似乎只能在Unity 3D中工作。这对我来说不好,因为我正在制作 2D 游戏,而且它不会以这种方式与“墙”发生碰撞。
我尝试将其重写为 2D,但使用向量时遇到了错误。
如果您能帮我将其重写为 2D,我将非常高兴。
以下是在 3D 中运行的代码:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class Drag : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown() {
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
对于使用此代码时遇到问题的人,我使用 ScreenPointToRay 来使用代数光线投射(快速)来确定对象应距离相机多远。这适用于正交相机和透视相机
此外,该对象可以使用Collider
能够被拖来拖去。所以没有必要使用[RequireComponent(typeof(BoxCollider2D))]
.
对我来说效果很好的最终代码是:
using UnityEngine;
using System.Collections;
public class DragDrop : MonoBehaviour {
// The plane the object is currently being dragged on
private Plane dragPlane;
// The difference between where the mouse is on the drag plane and
// where the origin of the object is on the drag plane
private Vector3 offset;
private Camera myMainCamera;
void Start()
{
myMainCamera = Camera.main; // Camera.main is expensive ; cache it here
}
void OnMouseDown()
{
dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
offset = transform.position - camRay.GetPoint(planeDist);
}
void OnMouseDrag()
{
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
transform.position = camRay.GetPoint(planeDist) + offset;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)