Hello! I’m trying to get an object (Lets call this one the ‘Planet’ object) to gravitate towards another object (Lets call this one the ‘Sun’ object). The way i did this is to have a trigger collider in the Sun object much larger than it and when the Planet object is inside said trigger collider, a force is applied to the Planet object towards the Sun object. However i’m trying to use OnTriggerStay2D to detect if the Planet object is in the trigger or not, but i cannot for the life of me figure how to get to work. The problem is that the OnTriggerStay2D function is not running at all, i know this because i have a Debug.Log function that displays text when it should be detecting something, but it’s not showing up in the console. Any pointers?
I know that other people had problems with OnTriggerStay2D and it’s variants, but i’ve read them but it’s still not working. Here is what i tried so far.
- Both the Sun and Planet objects have Rigidbody2Ds on them, with the Sleeping Mode set to ‘Never Sleep’
- The Sun’s rigidbody is Kinematic (I want it to be static for simplicity).
- Gravity is disabled.
- Each object is attached to thier own individual empty gameObjects
- I am using 2D colliders/triggers for both objects.
Here is my code, it is attached to my Sun object.
using UnityEngine;
using System.Collections;
public class GravityRuntime : MonoBehaviour {
Rigidbody2D affected;
private Vector2 gravityDir;
public bool debugLines;
void Start () {
Debug.Log ("Starting");
}
void OnTriggerStay2D (Collider2D influenced) {
Debug.Log ("Collider Detected");
affected = influenced.GetComponent<Rigidbody2D> ();
Vector2 influencepos = influenced.transform.position;
Vector2 starpos = gameObject.transform.position;
gravityDir = new Vector2(influencepos.x - starpos.x, influencepos.y - starpos.y);
if (debugLines == true) {
Gizmos.DrawRay(affected.transform.position, gravityDir);
}
affected.AddForce (gravityDir * 10);
}
}
(Note: I know gravity falls off by the inverse square law, but the AddForce part is a placeholder.)
So, what do you think? Keep in mind that this is my first question and i probably missed some useful guidelines, if so please feel free to tell me.
Have an excellent day!