Search Unity

Can't move gameObject using rigidbody.MovePosition()

Discussion in 'Scripting' started by gangstapug, Aug 16, 2019.

  1. gangstapug

    gangstapug

    Joined:
    Jan 14, 2019
    Posts:
    3
    Hi guys, I'm trying to create a player controller by using rigidbodies.

    void Movement()
    {
    float xInput = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
    float zInput = Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime;

    Vector3 zCurrentPosition = transform.position + (transform.forward * zInput);
    Vector3 xCurrentPosition = transform.position + (transform.right * xInput);

    rb.MovePosition(zCurrentPosition); //forward Movement
    rb.MovePosition(xCurrentPosition); //side Movement
    }
    I don't quite understand why I can get one Input to work at a time, but not both inputs. If I were to remove rb.MovePosition(xCurrentPosition) then rb.MovePosition(zCurrentPosition) would be able to work. But adding both lines of code makes rb.MovePosition(zCurrentPosition) unable to work.
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    When you're doing this:

    Code (csharp):
    1. rb.MovePosition(zCurrentPosition);
    You're setting the position of the rigidbody to zCurrentPosition.
    When on the very next line you do this:

    Code (csharp):
    1. rb.MovePosition(zCurrentPosition);
    You're also directly setting the position, overwriting the result of the last line of code.

    What you want too do is to accumulate the movement into one variable:

    Code (csharp):
    1. // instead of:
    2. Vector3 zCurrentPosition = transform.position + (transform.forward * zInput);
    3. Vector3 xCurrentPosition = transform.position + (transform.right * xInput);
    4.  
    5. //Do
    6. Vector3 newPosition = transform.position + (transform.forward * zInput) + (transform.right * xInput);
    7.  
    8. //Instead of
    9. rb.MovePosition(zCurrentPosition); //forward Movement
    10. rb.MovePosition(xCurrentPosition); //side Movement
    11.  
    12. //Do:
    13. rb.MovePosition(newPosition);
     
    gangstapug likes this.
  3. gangstapug

    gangstapug

    Joined:
    Jan 14, 2019
    Posts:
    3

    Wow this helped alot! thank you kind sir!:D