-2

I have a problem. I'm making a game what is a lot depending on gravity. now I want that the player object has a gravity to other objects with a certain tag. It is a 2d game. How can I give the player this kind of gravity? I prefer a c# script, but java is also fine.

Thanks for your help!

Steven
  • 166,672
  • 24
  • 332
  • 435
Florian
  • 11
  • 1

1 Answers1

-1

Create a script with a FixedUpdate method and inside this method calculate and apply rigidbody forces.

Use Newton's Law of Universal Gravitation for calculating the strength of gravity in the script. Within the loop of the script, each individual gravity vector is calculated and then summed up to the final gravitational vector, which is the direction the gameobject is to be pulled towards.

For example (C#):

// Attach this script to gameObject that will be affected by gravity
// Ensure gameObject has rigidbody component attached and "Use Gravity" is UNCHECKED
public class GravityScript : MonoBehaviour
{

    Rigidbody rigidbody;
    Transform[] gravitySources; // Assign each Transform in inspector, these will be sources of gravity.

    void Start ()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    // NOTE: Include proper individual gravitational forces (gravity from far away objects is weaker than gravity from closer objects)
    private Vector3 CalculateGravity()
    {
        Vector3 gravity = Vector3.zero;

        // For each source of gravity accumulate total gravitational force
        foreach (Transform source in gravitySources)
        {
            // Direction of gravity
            Vector3 direction = transform.position - source.position;
            // Calculate strength of gravity at distance
            float gravitationalStrength = Vector3.Distance(transform.position, source.position) * ????;
            gravity += direction.normalized * gravitationalStrength;
        }

        return gravity;
    }

    void FixedUpdate ()
    {
        Vector3 gravity = CalculateGravity();
        rigidbody.AddForce(gravity, Forcemode.Acceleration);
    }
}
Jayson Ash
  • 709
  • 1
  • 5
  • 8