unity 关于2d物体点击后能拖动的代码

好几天没写博客了,懒散了。今天又开始记录了,关于前几天遇见的一些东西。 关于2D物体点击后能拖动的代码,必须加上2D的Collider 和钢体(Rigidbody 2D)不然脚本没用。

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

private bool drag;					// 如果被拖动,则为真
private Rigidbody2D myRigidbody;	//如果我引用GameObject's Rigidbody2Ds被拖动,则为True
private bool wasKinematic;			// Flag indicating whether or not the Ridigbody

// Use this for initialization
void Start () 
{
	myRigidbody = GetComponent();

	wasKinematic = myRigidbody.isKinematic;
}

// Update is called once per frame
void Update () 
{
	if (drag == true) 
	{
		DragFunction();
	}
}

// 检查是否按下鼠标按钮
void OnMouseDown() 
{
	drag = true;

	myRigidbody.isKinematic = true;
}

// 检查鼠标按钮是否被释放
void OnMouseUp() 
{

    // 更新文件
	if (drag == true)
		myRigidbody.isKinematic = wasKinematic;
		drag = false;
}

void DragFunction() {
    // 我们正在将2D鼠标坐标转换为3D

	float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;

	Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen ));

    //更新GameObject位置

	transform.position = new Vector3( pos_move.x, pos_move.y, pos_move.z );
	
}

}

你可能感兴趣的:(unity 关于2d物体点击后能拖动的代码)