0
\$\begingroup\$

So i've been trying to make the player face towards the direction i pressed. That part works just fine but when I try to move the player it moves diagonally instead of left/right. Any clues?

 if (Input.GetKey(KeyCode.RightArrow))
             {
                 //moves the player
                 rb2d.velocity = new Vector3(2.5f, 0, 0);
                 transform.Translate(rb2d.velocity * Time.deltaTime);

                 //flips the player right
                 if (human.flipY == true)
                 {
                     human.transform.rotation = Quaternion.Euler(0, 0, 270);
                 }
                 else
                 {
                     transform.rotation = Quaternion.Euler(0, 0, -270);
                 }
\$\endgroup\$
2
  • \$\begingroup\$ I assume (from rb2d variable name) you are using Rigidbody2D for all the movement. Now, if its mode is not selected as 'Kinematic' (it is Dynamic by default), the Rigidbody2D will be affected by gravity, thus making the player move diagonally. \$\endgroup\$
    – eLTomis
    Apr 9, 2020 at 8:14
  • \$\begingroup\$ I tried it changing to kinematic as you said but unfortunately it still moves diagonally when left/right is pressed \$\endgroup\$ Apr 9, 2020 at 9:05

1 Answer 1

1
\$\begingroup\$

When in doubt, remember to read the documentation for the methods you're using:

If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes.

So you're getting a velocity vector in world space, and applying it as a local-space translation. This will rotate the vector by your local orientation.

It sounds like your local orientation is twisted +- 90 degrees from world space. So the rigid body velocity tries to move you to the world's right, and transform.Translate tries you to the object's right (which points up or down in the world), resulting in a net movement that's diagonal.

Really, you should not have transform.Translate here at all. If your object has a rigid body (2D or 3D), you should consider setting transform.position/rotation, transform.Translate()/Rotate() to be off-limits. Moving a physics object via its transform makes your code fight with the physics engine for control, leading to all kinds of unwanted outcomes as you've already observed. Use velocity, angular velocity, AddForce, MovePosition or MoveRotation instead to keep your movement in the physics engine's control.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .