Search code examples
unity-game-enginegame-physics

Character is not moving foward when setting body type to Dynamic


Currently I have 1 problem when moving character toward x position using this code

     Vector3 temp = transform.position;
     temp.x += forwardSpeed * Time.deltaTime;
     transform.position = temp;

Below is the settings of inspector

enter image description here

If I set body type to Dynamic character can move up and down but if I set body type to Kinematic character can move foward but when I click to the screen character will jump out of the screen.

Below is my source code and I hope everyone can point me out what I have done wrong

My source code


Solution

  • You should be using Rigidbody2D.MovePosition to move rigidbodies.

    Vector3 temp = transform.position;
    temp.x += forwardSpeed * Time.deltaTime;
    
    var rb = GetComponent<Rigidbody2D>();
    rb.MovePosition(temp);
    

    You can also use rb.position = temp but MovePosition() provides the best collision detection.


    If this doesn't work either, you have colliders blocking your rigidbody in the forward direction, preventing it from moving that way. In that case, check the object's hierarchy, including its children.