how can i make game object to orbit another (using rigidbody2d)
i would like gameobject with rigidbody2d to orbit around the target point. i want to use physics with my gameobject to attain this functionality. Please help me with this Thank you Amir Yatoo
You can simply simulate gravity. The equation to get the force exacted by gravity on an object given the mass of the attracter, distance to attracter, and gravitational constant is
g = GM/r^2
where G is the gravitational constant (strength of gravity per unit of mass), M is the mass of the attracting object, and r is the distance between the center of the attracting object and the object being attracted.
Here’s a quick script I wrote.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbiterScript : MonoBehaviour {
public GameObject attracter; // Set this to the gameobject that this gameobject will be attracted to
public float gravityConstant; // Affects strength of gravity
public Vector2 startVelocity; // This will be the starting velocity of our second object (it needs to have velocity in order to orbit)
private Rigidbody2D rb;
private float attracterMass;
// Use this for initialization
void Start () {
rb = this.GetComponent<Rigidbody2D>();
attracterMass = attracter.GetComponent<Rigidbody2D>().mass;
rb.velocity = startVelocity;
}
// FixedUpdate is called once per physics update
void FixedUpdate () {
float distance = Vector2.Distance(this.transform.position, attracter.transform.position); // Distance between us and attracter
Vector2 unrotatedForce = (Vector2.right * gravityConstant * attracterMass) / Mathf.Pow(distance, 2); // Magnitude of force due to gravity
// Now we have to rotate that force so it's pointing towards the attracter
Vector2 posDifference = attracter.transform.position - this.transform.position; // Difference in position
float angleDifference = Mathf.Atan2(posDifference.y, posDifference.x); // Now, difference in angle
// Now we use some trig to rotate the force vector from pointing right to pointing at the attracting object
Vector2 rotatedForce = new Vector2(unrotatedForce.x * Mathf.Cos(angleDifference) - unrotatedForce.y * Mathf.Sin(angleDifference),
unrotatedForce.x * Mathf.Sin(angleDifference) + unrotatedForce.y * Mathf.Cos(angleDifference));
// And now we simply add the force to our rigidbody
rb.AddForce(rotatedForce);
}
}
Simply attach this script to a Sprite or some other 2D object with an associated Rigidbody2D, set the “Attracter” field to a reference of the object that this object is rotating around, then set the gravity constant (force of gravity multiplier) and starting velocity, and you’re good to go.