P
P
Parasat Utebay2017-04-09 08:09:34
C++ / C#
Parasat Utebay, 2017-04-09 08:09:34

How to make real planetary gravity in Unity?

I want to create a game with a round planet and with normal gravity, and so that objects obey the laws of physics and that the player is always horizontal to the ground (as in Super Mario Galaxy), but I don’t know how.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deerenaros, 2017-04-09
@Persey14

Hello. I am Kirill. I would like you to make a game, 3D action is the essence of this... User can play wood elves, palace guard and villain. And if the user plays as elves, then elves in the forest, wooden houses are crowded with soldiers of the palace and villains. You can rob cows...

We make a lot of meshes (a planet in the form of a ball, a player, etc.), add to them something like this script:
class Gravity : MonoBehaviou {
    static const double G = 9.8; // correct constant here

    static LinkedList<Gravity> meshes = new LinkedList<Gravity>();

    float Mass {
        get {
            return GetComponent<Rigidbody>().mass;
        }
    }

    void Start() {
        meshes.add(this);
    }

    void Update() {
        foreach(var mesh in meshes) {
            float power = (float)(G*Mass*mesh.mass);
            var force = power*(mesh.transform.position - transform.position).normalized;
            force /= (mesh.transform.position - transform.position).sqrMagnitude;
            GetComponent<Rigidbody>().AddForce(force);
        }
    }
}

Let's leave horizontality as homework. Hint - you need to rotate the player mesh so that it is aligned with the ground-player vector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question