gpt4 book ai didi

c# - 在 Unity 2D 中拖动对象

转载 作者:可可西里 更新时间:2023-11-01 08:08:47 26 4
gpt4 key购买 nike

我一直在寻找适用于 Unity 2D 的对象拖动脚本。我在网上找到了一个很好的方法,但它似乎只适用于Unity 3D。这对我不利,因为我正在制作 2D 游戏并且它不会以这种方式与“墙壁”发生碰撞。

我曾尝试将其重写为 2D,但使用 Vectors 时遇到了错误。

如果你能帮我把它改写成二维的,我会很高兴。

这是在 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;
}
}

关于c# - 在 Unity 2D 中拖动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23152525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com