拖动鼠标即可在其自己的X轴上来回移动对象

时间:2018-10-31 05:08:07

标签: c# unity3d

Image

我要:

  1. 使用鼠标在其自己的X轴上来回移动特定对象。
  2. 限制该框间隙之间的移动

我尝试过但对我不起作用的代码:

    void Update()
    {
    point = Camera.main.ScreenToWorldPoint(
    new Vector3(Input.mousePosition.x,
            (transform.position.y-Camera.main.transform.position.y),
            (transform.position.z-Camera.main.transform.position.z)));

    point.y = transform.position.y;                   
    point.z = transform.position.z;
    transform.position = point;
  }

1 个答案:

答案 0 :(得分:0)

要钳位一个值,可以使用Mathf.Clamp()方法。

完整的解决方案可能看起来像这样:

将脚本添加到杠杆对象:

using UnityEngine;
using UnityEngine.EventSystems;

public class MoveOnMouseDrag : MonoBehaviour {

    public float halfDistance;

    void Start()
    {
        EventTrigger trigger = GetComponent<EventTrigger>();
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.Drag;
        entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); });
        trigger.triggers.Add(entry);
    }

    public void OnDragDelegate(PointerEventData data)
    {
        float distanceFromCamera = Vector3.Distance(Camera.main.transform.position, transform.position);
        var newPos = Camera.main.ScreenToWorldPoint(new Vector3(data.position.x, data.position.y, distanceFromCamera));

        transform.position = new Vector3(Mathf.Clamp(newPos.x, -halfDistance, halfDistance),
                                         transform.position.y,
                                         transform.position.z);
    }
}

为了使脚本起作用,您必须将EventTrigger组件添加到同一对象,将EventSystem添加到场景,将PhysicsRaycaster组件添加到摄像机。