michaeldodell
michaeldodell

Reputation: 37

Changing gravity on an object depending on, say, altitude

I am using unity and trying to figure out gravity for 2D objects. Am I able to change something's gravity depending on its position in a world or space or will the gravity remain the same for the whole world?

Meaning if I have an object at a specific gravity at altitude zero and then once the object gets to 1000 meters the gravity changes.

Upvotes: 1

Views: 284

Answers (1)

Fattie
Fattie

Reputation: 12631

Just a very quick answer,

  1. Learn about Physics2D.gravity. Put a few objects in a scene (balls, whatever) and let the scene run, notice they fall. Try varying gravity and notice the acceleration is different.

Master all of that before proceeding to step 2!

Now the bad news!

"Ordinary gravity" in Unity is very easy as you can see. Unfortunately if you want to do individual gravity on different objects, it's pretty advanced!

  1. Basically turn off the "overall gravity" from (1) which Unity gives your easily for free. Then you have to manually add gravity to every object (you want it on!)

Basically you do something like this ...

public float gravity;
  void FixedUpdate () {
    rigidbody2D.AddForce(Vector3.down * 9 * rigidbody2D.mass);
}

Unfortunately you have a lot to learn about the run loop, physics (ie, actual real world physics!), game objects, rigidbodies and C# in general.

Master all of that before proceeding to step 3!!

  1. Finally you want gravity to vary by altitude (for certain objects). Basically then just do something like this:

For example, gravity weakens as you go up .. a' is your altitude

public float gravity;
  void FixedUpdate () {
    f = (1000.0 - a) / 1000.0
    rigidbody2D.AddForce(Vector3.down * 9 * f * rigidbody2D.mass);
}

A lot to learn!

Upvotes: 4

Related Questions