1
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – some rand Jul 1 '19 at 23:39
1
\$\begingroup\$

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
    _rb.AddForce(gravityDirection);
}

You can leave the ForceMode as the default, impulse is meant for instantaneous things like collisions (see here).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.