简体   繁体   English

平稳地包裹刚体

[英]Smoothly lerp a rigidbody

I'm wanting my player to move to the left when the player hits the left of the screen. 我希望播放器触及屏幕左侧时,播放器向左移动。 Right now, my player only moves as and when I hold down my mouse button. 现在,当我按住鼠标按钮时,播放器只会移动。 What I'm really wanting is for him to continually move to the left until he hits the target position when I press the screen once. 我真正想要的是让他不断向左移动,直到我按一下屏幕时他到达目标位置。

Can someone please tell me what I'm missing from my code to allow this to happen? 有人可以告诉我代码中缺少的内容吗?

void FixedUpdate() 
{

    if(Input.GetMouseButtonDown(0))
    {
        if(Input.mousePosition.x < (Screen.width*2)/3 && Input.mousePosition.y > Screen.height/3)
        {
            if(position == middle)
            {
                MoveLeft();
            }   
        }
    }
}

void MoveLeft()
{
    var pos = rigidbody.position;
    float xPosition = left.transform.position.x;
    pos.x = Mathf.Lerp(pos.x, xPosition, speed * Time.deltaTime);
    rigidbody.position = pos;
}

My method is in the FixedUpdate because I'm moving the players rigidbody as oppose to translating the actual player. 我的方法在FixedUpdate中,因为我正在移动播放器刚体,以反对转换实际播放器。

Right now the player only moves when you hit mouse button because that's how your code is written: you check if the mouse is pressed every frame, and only if it is move the rigidbody. 现在,播放器仅在您按下鼠标按钮时移动,因为这就是编写代码的方式:您检查是否在每一帧都按下了鼠标,并且只有在移动刚体时才检查。

If you want the player to move regardless of whether the mouse is still pressed or not, you should create some kind of variable to save the state of the player, and set to move left when the mouse button is pressed and set it to stop when the player reaches his target. 如果要让播放器移动而无论是否仍按下鼠标,都应创建某种变量以保存播放器的状态,并设置为在按下鼠标按钮时向左移动,并在出现以下情况时停止移动玩家达到了目标。

If I correctly understood your goal, it would look something like this: 如果我正确理解了您的目标,它将看起来像这样:

bool moveLeft = false;

void FixedUpdate() 
{

    if(Input.GetMouseButtonDown(0)
        && (Input.mousePosition.x < (Screen.width*2)/3 && Input.mousePosition.y > Screen.height/3))
    {
        moveLeft = true;
    }

    if (moveLeft
        && (position == middle))
    {
        MoveLeft();
    }
    else
    {
        moveLeft = false;
    }
}

void MoveLeft()
{
    var pos = rigidbody.position;
    float xPosition = left.transform.position.x;
    pos.x = Mathf.Lerp(pos.x, xPosition, speed * Time.deltaTime);
    rigidbody.position = pos;
}

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

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