Zwi*_*bel 14 c# drag unity-game-engine
我已经为Unity 2D寻找了一个对象拖动脚本.我在互联网上找到了一个很好的方法,但它似乎只是在Unity 3D中工作.这对我来说并不好,因为我正在制作一个2D游戏并且它不会以这种方式与"墙壁"发生碰撞.
我曾尝试将其重写为2D,但我已经使用Vectors崩溃了.
如果你能帮我把它重写成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;
}
}
Run Code Online (Sandbox Code Playgroud)
你快到了.
将代码中的RequireComponent行更改为:
[RequireComponent(typeof(BoxCollider2D))]
Run Code Online (Sandbox Code Playgroud)
并将BoxCollider2D组件添加到您添加脚本的对象.我只是测试它,它工作正常.
对于使用此代码有问题的人,我删除screenPoint并替换它10.0f (这是对象与相机的距离).你可以使用你需要的任何浮动.现在它有效.对象也需要BoxCollider或者CircleCollider能够被拖动.所以没有必要使用[RequireComponent(typeof(BoxCollider2D))].
对我来说很好的最终代码是:
using UnityEngine;
using System.Collections;
public class DragDrop : MonoBehaviour {
private Vector3 offset;
void OnMouseDown()
{
offset = gameObject.transform.position -
Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
}
void OnMouseDrag()
{
Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f);
transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
}
}
Run Code Online (Sandbox Code Playgroud)