简体   繁体   English

C#-在鼠标拖动时,游戏对象在单个轴上跟随鼠标。 2D

[英]C# - On Mouse Drag Game Object follows Mouse on a single Axis. 2D

I'm trying to create a 2d game and the game objects should follow the mouse on a single axis (the x axis), when the user drags the object. 我正在尝试创建2D游戏,并且当用户拖动对象时,游戏对象应在单个轴(x轴)上跟随鼠标。

  1. Starting Point 初始点 在此处输入图片说明

  2. When i moved that shouldnt go up or down. 当我移动时,不应该向上或向下。 在此处输入图片说明

Here's my code, the problem is, the game object is following the mouse everywhere i drag. 这是我的代码,问题是,在我拖动的任何地方,游戏对象都跟随鼠标。

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

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");

        this.transform.position = eventData.position;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }
}

You are currently changing all axis(x,y,z) with this.transform.position = eventData.position; 您当前正在使用this.transform.position = eventData.position;更改所有轴(x,y,z) this.transform.position = eventData.position; . Only change the x-axis. 仅更改x轴。 Use eventData.position.x only. 仅使用eventData.position.x

public void OnDrag(PointerEventData eventData)
{
    Debug.Log("OnDrag");
    Vector3 tempPos = this.transform.position;
    tempPos.x = eventData.position.x;
    this.transform.position = tempPos;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM