首页 > 解决方案 > Changing the player's position in Update() or FixedUpdate() method?

问题描述

In my game I've a case that when the player is touching the collider of a specific GameObject and the player press the X key I want to change his position to the position of another GameObject.

To do that I use the following code

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.X))
    {
        // Check Colliders collition
        // End of Check Colliders collition

        var playerRigidBody = GetComponent<Rigidbody2D>();
        playerRigidBody.position = AnotherObject.transform.position;
    }
}

I've realized that very often when I press the X key the player don't change his position to the position of the other GameObject. However if I move the code to the Update() method it works as expected (with no delay).

But I've read in the official documentation and in a lot of blogs that the code related to physics and Rigidbodies must be put in the FixedUpdate instead of Update

So the question is the following:

For this case putting the code in the Update() method is not recommended? (Note that I'm not using forces nor torques)

If it's not recommended then how can I assure that every time the player press the X key he will change his position to the other GameObject position in FixedUpdate()?

标签: c#unity3d

解决方案


In general if you want a smooth movement you should rather use MovePosition in FixedUpdate otherwise everything regarding Physics (so also RigidBody) you should always do in FixedUpdate (as explained in the API there as well).


You should however catch the GetKeyDown in Update and split those two things:

bool wasClicked;
RigidBody playerRigidBody;

void Start()
{
    // do this only once!
    playerRigidBody = GetComponent<Rigidbody2D>();
}

void Update()
{
    // Catch user input here

    if (Input.GetKeyDown(KeyCode.X))
    {
        wasClicked = true;
    }
}

void FixedUpdate()
{
    // Handle physics here

    if(!wasClicked) return;

    playerRigidBody.position = AnotherObject.transform.position;

    wasClicked = false;
}

推荐阅读