bigchungus23
bigchungus23

Reputation: 33

Unity 2D: Gravitational Pull

I'm working on a small game: I want all GameObjects to be pulled into the middle of the screen where they should collide with another GameObject.

I tried this attempt:

using UnityEngine;
using System.Collections;
public class Planet : MonoBehaviour
{
    public Transform bird;
    private float gravitationalForce = 5;
    private Vector3 directionOfBirdFromPlanet;
 
    void Start ()
    {
        directionOfGameObjectFromMiddle = Vector3.zero;
    }
 
    void FixedUpdate ()
    {
        directionOfGameObjectFromMiddle = (transform.position-bird.position).normalized;
        bird.rigidbody2D.AddForce (directionOfGameObjectFromMiddle * gravitationalForce);    
    }
}

sadly I can't get it to work. I've been told that I have to give the object that is being pulled another script but is it possible to do this just with one script that is used on the object that pulls?

Upvotes: 1

Views: 1336

Answers (1)

derHugo
derHugo

Reputation: 90659

So first you have a lot of typos / code that doesn't even compile.

You use e.g. once directionOfBirdFromPlanet but later call it directionOfGameObjectFromMiddle ;) Your Start is quite redundant.

As said bird.rigidbody2D is deprecaded and you should rather use GetComponent<Rigidbody2D>() or even better directly make your field of type

public Rigidbody2D bird;

For having multiple objects you could simply assign them to a List and do

public class Planet : MonoBehaviour
{
    // Directly use the correct field type
    public List<Rigidbody2D> birds;

    // Make this field adjustable via the Inspector for fine tuning
    [SerializeField] private float gravitationalForce = 5;

    // Your start was redundant    

    private void FixedUpdate()
    {
        // iterate through all birds
        foreach (var bird in birds)
        {
            // Since transform.position is a Vector3 but bird.position is a Vector2 you now have to cast
            var directionOfBirdFromPlanet = ((Vector2) transform.position - bird.position).normalized;

            // Adds the force towards the center
            bird.AddForce(directionOfBirdFromPlanet * gravitationalForce);
        }
    }
}

Then on the planet you reference all the bird objects

enter image description here

On the birds' Rigidbody2D component make sure to set

Gravity Scale -> 0

you also can play with the Linear Drag so in simple words how much should the object slow down itself while moving

E.g. this is how it looks like with Linear Drag = 0 so your objects will continue to move away from the center with the same "energy"

enter image description here

this is what happens with Linear Drag = 0.3 so your objects lose "energy" over time

enter image description here

Upvotes: 3

Related Questions