使用鼠标位置Unity3D移动对象时出现问题

时间:2019-04-15 17:34:47

标签: c# unity3d

我使脚本在下面移动时可以在鼠标位置平滑移动对象,但是平滑运行,但是在此脚本中存在一个问题,当我单击并移动鼠标时,对象立即移动到(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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我想我了解您想要的东西。

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

否则,您可以使用

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

但是我不明白为什么您用currentSwipe来划分200 ..您可能有自己的理由。

无论如何,据我所知,您还需要另外存储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的方式实际上无法到达确切位置……它只会变得非常接近而且非常缓慢。

相关问题