movement on 2d planets in unity code example
Example: Move player on planets in unity 2d
public float gravity;
public void Attract(Transform body)
{
Vector2 gravityUp = (body.position - transform.position).normalized;
Vector2 bodyUp = body.up;
Rigidbody2D rb2d;
rb2d = body.GetComponent<Rigidbody2D>();
rb2d.AddForce (gravityUp * gravity);
Quaternion targetRotation = Quaternion.FromToRotation (bodyUp, gravityUp) * body.rotation;
body.rotation = Quaternion.Slerp (body.rotation, targetRotation, 50 * Time.deltaTime);
}
public GravityAttractor attractor;
private Transform thisTransform;
private Rigidbody2D rb2d;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
thisTransform = transform;
}
void Update ()
{
attractor.Attract (thisTransform);
}
PlayerController public float moveSpeed = 15;
private Rigidbody2D rb2d;
private Vector2 moveDir;
void Start()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void Update ()
{
moveDir = new Vector2 (Input.GetAxisRaw ("Horizontal"), 0).normalized;
}
void FixedUpdate ()
{
Vector2 globalmovedir = (transform.TransformDirection(moveDir));
rb2d.position += globalmovedir * moveSpeed * Time.fixedDeltaTime
}