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
@santafeast You should have the orbiting object get a direction to the object it is orbiting every frame and then add force in that direction and also have a force added at 90 degress to that direction as an initial impulse so the objects dont collide. You can also make forces depend on masses of objects and implement third newtons law to have everything have gravity…But for simple behaviour here is my script.
Here I wrote it for ya:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Orbit : MonoBehaviour {
public Transform objectToOrbit;
Rigidbody2D rb;
[Header("USING VELOCITY(Using Initial Impulse = false)")]
public float orbitSpeed; //20
public float gravityVelocity; //1
[Header("Using Initial Impulse")]
public float gravity; //20
public float initialImpulse; //500
public bool usingInitialImpulse; //IF FALSE WILL USE VELOCITY
Vector2 direction;
void Start(){
rb = GetComponent<Rigidbody2D> ();
if (usingInitialImpulse == true) {
direction = objectToOrbit.transform.position - transform.position;
transform.right = direction;
rb.AddForce (transform.up * initialImpulse);
}
}
void Update(){
if (objectToOrbit.gameObject != null) {
//GETTING DIRECTION
direction = objectToOrbit.transform.position - transform.position;
//SETTING THE X(RED)(transform.right) AXIS TO POINT AT OUR TARGET (AND SO WE SET THE GREEN AS WELL CAUSE IT WILL ALWAYS BE AT 90 DEGRESS TO RED
transform.right = direction;
Debug.DrawRay (transform.position, transform.right*100, Color.red);
Debug.DrawRay (transform.position, transform.up*100, Color.green);
//HERE WE CREATE THE GRAVITATIONAL BEHAVIOUR
if (usingInitialImpulse) {
rb.AddForce (transform.right * gravity);
} else {
rb.velocity = transform.right * gravityVelocity + transform.up * orbitSpeed;
}
//PRINTING DISTANCE
print(Vector3.Distance(objectToOrbit.position,transform.position));
}
}
}