Hi all, I’m trying to create a planetary body type script to have objects fall in and out of orbit based on their original velocity multiplied by the force of gravity emitted by the planet in the direction of the planet.
I’ve tried what I thought would have worked, but for some reason absolutely nothing is happening to my objects (the script is attached to them).
They are prefabs that are instantiated at random locations but when they collide with the gravity trigger I need them to have force added to them in the direction of the planet.
Here is what I’ve got so-far:
public float gravityAmount = 100;
float moveSpeed;
Rigidbody2D rb;
public GameObject ball;
bool insideGravity;
void Awake()
{
ball = GameObject.FindGameObjectWithTag("Damager");
}
void Start()
{
insideGravity = false;
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
ball = GameObject.FindGameObjectWithTag("Damager");
if (insideGravity)
{
//This line is the trouble I'm pretty sure.
rb.AddForce((ball.transform.position - transform.position) * gravityAmount * Time.smoothDeltaTime);
}
Vector2 movement = new Vector2(xDirection, yDirection).normalized;
rb.velocity = movement * moveSpeed;
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Magnet")
{
insideGravity = true;
}
}
}
I also thought it could have been using both AddForce and velocity at the same time so I tried using this line instead:
rb.velocity = ball.transform.position - transform.position * gravityAmount * Time.smoothDeltaTime;
But still no change. I’d really appreciate any help you can give me, thanks!