允许玩家在Unity中拖动对象

时间:2019-02-17 21:52:03

标签: unity3d vector drag-and-drop game-engine drag

我目前正在Unity中制作游戏,希望玩家能够根据触摸位置将对象拖出整个屏幕。为此,我创建了一个脚本,据我所知,它没有任何错误,应该允许我将脚本附带的对象拖到整个屏幕上。但是,当我尝试执行代码时,什么也没有发生。当触摸时,该对象保持静态,并且完全不移动。我什至尝试将其Input.GetTouch(0).position切换到Input.mousePosition,以查看问题出在我的手机上,但这还是可行的。有谁知道我怎么能解决这个问题?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class MoveBall : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public static GameObject WhiteBall;
    Vector3 startPosition;

    #region IBeginDragHandler implementation

    public void OnBeginDrag(PointerEventData eventData)
    {
        WhiteBall = gameObject;
        startPosition = transform.position;
    }

    #endregion

    #region IDragHandler implementation

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.GetTouch(0).position;

    }

    #endregion

    #region IEndDragHandler implementation

    public void OnEndDrag(PointerEventData eventData)
    {
        WhiteBall = null;
        transform.position = startPosition;
    }

    #endregion



}

1 个答案:

答案 0 :(得分:2)

即使您希望为移动设备触摸输入,也可以使用OnMouseDrag功能。只需将对撞机附加到gameObject上,然后将代码简化为以下内容:

using UnityEngine;

public class MoveBall : MonoBehaviour
{

    private void OnMouseDrag()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = mousePos;
    }
}