# How do I change the gravity to just one object

I'm making a 2d game on unity and I have a player who needs to walk on the four walls of a room, so I made him a rigidbody so it can change the gravity. But my game has enemies too and when the player changes the gravity the enemy is affected too (I just want them to move up/down in a pattern). How do I change the gravity to one specific object?

• Use add force on it and i think you should set force mode to impulse, if not impulse that something else. I remember i done this when i was making hover car. – some rand Jul 1 '19 at 23:39

You can change the gravityScale of a single Rigidbody2D, but that would only work for up/down. For any direction, the simplest way would be to just implement gravity yourself, and either set the gravity in the physics settings to 0,0 or set the gravityScale of the player's rigidbody to 0 if you want the enemies to use the default gravity system.

Something like this should work:

public Vector2 gravityDirection; // new Vector2(0, -9.81f) could be the default
private Rigidbody2D _rb;
void Awake() {
_rb = GetComponent<Rigidbody2D>(); // cache reference since GetComponent is expensive
}

void FixedUpdate(){  // use FixedUpdate for physics stuff