I am trying to make one game object orbit a star by having a rigidbody look at the star and the planet itself is a child of the rigidbody. heres my code:
using UnityEngine;
using System.Collections;
public class Orbit : MonoBehaviour {
public Vector3 Force;
public Transform Target;
void FixedUpdate()
{
transform.LookAt(Target);
rigidbody.AddRelativeForce(Force);
}
}
the Problem is that when i use this, the rigidbody looks at the star, but it does not move sideways relatively so that it will “orbit”, it simply moves sideways without turning. How can i fix this?
here is a little sample code. if you add a rigidbody to your object and play with drags you can set up a pretty orbit. would be better modelling the forces
#pragma strict
var target : Transform;
private var dir : Vector3;
private var forward : Vector3;
private var side : Vector3;
private var cross : Vector3;
function Start () {
forward = transform.forward; //forward vector just to have it (in 3d you need a plane to calculate normalvector, this will be one side of the plane)
dir = target.transform.position - transform.position; //direction from your object towards the target object what you will orbit (the other side of the plane)
side = Vector3.Cross(dir, forward); //90 degrees (normalvector) to the plane closed by the forward and the dir vectors
}
function Update () {
dir = target.transform.position - transform.position;
transform.LookAt(dir.normalized); // look at the target
rigidbody.AddForce(dir.normalized * 50);//add gravity like force pulling your object towards the target
cross = Vector3.Cross(dir, side); //90 degrees vector to the initial sideway vector (orbit direction) /I use it to make the object orbit horizontal not vertical as the vertical lookatmatrix is flawed/
rigidbody.AddForce(cross.normalized * 50); //add the force to make your object move (orbit)
}
you need the drag value to work against these forces or your object will fly away on a spiral the bigger the drag the smaller the orbit range