我正在开发拖放式2d教育游戏,并且坚持使用此代码。
当我尝试从pos1到pos2时,它可以工作。但是,我可以再次从pos2到pos1,这是我不想要的。
我尝试了一些代码但出现了一些错误
是否可以使用PointerEventData
解决此问题?
public class Manager : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Vector2 pos1;
public GameObject pos2;
void Start()
{
pos1 = transform.position;
}
public void OnBeginDrag(PointerEventData eventData)
{
debug.log(eventData)
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
}
else
{
transform.position = pos1;
}
}
}
答案 0 :(得分:2)
在这里,我重新编写了代码,其中包含一个bool,它限制了对象何时可以移动和不能移动。
using UnityEngine;
using UnityEngine.EventSystems;
public class Manager : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Vector2 pos1;
public GameObject pos2;
private bool canMove;
void Start()
{
pos1 = transform.position;
canMove = true;
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log(eventData);
}
public void OnDrag(PointerEventData eventData)
{
if (canMove)
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, pos2.transform.position);
if (distance < 50)
{
transform.position = pos2.transform.position;
transform.localScale = pos2.transform.localScale;
canMove = false;
}
else
{
transform.position = pos1;
}
}
}