【问题标题】:Issue when moving object with mouse position Unity3D使用鼠标位置 Unity3D 移动对象时的问题
【发布时间】:2019-04-16 02:33:24
【问题描述】:

我制作了下面的脚本,用鼠标位置平滑移动对象,它运行顺利,但我在这个脚本中有一个问题,当我点击并移动鼠标时,对象立即移动到 (0, 0, 0) 位置然后它开始随着鼠标的移动而移动。

我该如何解决这个问题,使对象从最后一个位置移动而不是从 (0, 0, 0) 位置移动?

脚本:

float Speed = 50f;
float sensitivity = 5f;

Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;

void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        firstPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    }

    if (Input.GetMouseButton(0))
    {
        secondPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);

        if (firstPressPos != secondPressPos)
        {
            transform.position = Vector2.Lerp(transform.position, new Vector3(currentSwipe.x / 200, currentSwipe.y / 200, transform.position.z), sensitivity * Time.deltaTime);
        }
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我想我明白你想要什么。

    您希望能够在任意位置单击,并且对象应该不仅仅是跟随鼠标的相对移动而不是确切的位置,对吧?

    否则你可以使用

    transform.position = Vector2.Lerp(transform.position, secondPressPos, sensitivity * Time.deltaTime)
    

    但我不明白你为什么将currentSwipe200 分开......你可能有你的理由。

    无论如何,我理解你想要的要求你还存储initialPos 对象在鼠标按钮按下时的位置。稍后您将 currentSwipe 添加到该初始位置,而不是单独使用它(= 将其添加到 0,0

    float Speed = 50f;
    float sensitivity = 5f;
    
    Vector2 firstPressPos;
    Vector2 secondPressPos;
    Vector2 currentSwipe;
    
    private Vector2 initialPos;
    
    void Update()
    {
    
        if (Input.GetMouseButtonDown(0))
        {
            firstPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    
            // store the current position
            initialPos = transform.position;
        }
        // I would just make it exclusive else-if since you don't want to 
        // move in the same frame anyway
        else if (Input.GetMouseButton(0))
        {
            secondPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    
            currentSwipe = secondPressPos - firstPressPos;
    
            if (firstPressPos != secondPressPos)
            {
                // Now use the initialPos + currentSwipe
                transform.position = Vector2.Lerp(transform.position, initialPos + currentSwipe / 200, sensitivity * Time.deltaTime);
            }
        }
    }
    

    请注意,通常这取决于您的需求,但那种使用 Lerp 的方式实际上从未到达确切位置……它只会变得非常接近且非常缓慢。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 2015-11-05
      相关资源
      最近更新 更多