1
\$\begingroup\$

I'm making a 2D game in Unity and I have a player character who needs to walk on the four walls of a room, so I gave them a Rigidbody so I 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 (the player character) without affecting others (the enemies)?

\$\endgroup\$
1
  • \$\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, 2019 at 23:39

2 Answers 2

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\$
1
  • \$\begingroup\$ You probably want to use ForceMode.Acceleration. The default (ForceMode.Force) takes the mass of the object into account. Gravity doesn't do that. \$\endgroup\$
    – Philipp
    Jan 24, 2023 at 23:14
2
\$\begingroup\$

You can set the gravityScale parameter on your Rigidbody2D component to zero to ignore the built-in gravity. Then you can add a ConstantForce2D component to the object, and set the force parameter to simulate a gravity force of any magnitude, in any direction. This lets you simulate gravity differently for each object you put this component onto.

Here's a YouTube tutorial that shows how to do something similar in 3D instead of 2D.

\$\endgroup\$
0

You must log in to answer this question.

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