Moving with transform.position creates stuttery movement and glitches

Hey guys, I have not done Unity for quite some years now, so bare with me!

I have created a script for moving my player, but the player object stutters a lot when touching other objects, and is even able to glitch through walls at times when spamming random movement.

Movement in a nutshell

 transform.position = new Vector3(transform.position.x + horizontalSpeed * Time.deltaTime, transform.position.y + verticalSpeed * Time.deltaTime, transform.position.z);

Player object
Box2D collider
RigidBody

  • Gravity Scale [0]
  • Body Type [Dynamic]
  • Collision detection [Continuous]
  • Interpolate [Interpolate]

My best guess is that I need to use addForce, as transform.position will try to teleport into the wall and eventually gets pushed out. Can I prevent this or is it best going with addForce instead?

Thanks in advance!

your guess is right, transform.position ignores colliders, so you will end up moving your player inside another collider and the physics will then try to resolve that which is the stutter/ pushing out

best way is to just go with the rigidbodies addforce

1 Like

if you want to use transform.position you need to check first if there is a collision on the position you are trying to move to

you can do a raycast on this position

new Vector3(transform.position.x + horizontalSpeed * Time.deltaTime, transform.position.y + verticalSpeed * Time.deltaTime, transform.position.z)

and if it returns true dont allow the move

1 Like

If you are using Transforms to move an object, specifically the player you should use Raycasts or BoxCast to check before you hit something

You should never directly manipulate Transforms to change the position/rotation of a Rigidbody2D as that is its role which is why it has an API dedicated to movement. It’s not there for any other reason.

1 Like

Makes sense - thanks :slight_smile:

Went for that solution and it worked - thanks a lot :slight_smile:

If you want to have similar movement to setting transform.position, but still interact with colliders, you can set your Rigidbody’s isKinematic property to true and use the Rigidbody.MovePosition method instead.

A kinematic Rigidbody basically means it will still interact with colliders, but it will not move from external forces such as gravity and other collisions.