Move player on planets in unity 2d code example
Example: Move player on planets in unity 2d
/*Hey, I found this script on reddit after hours of searching,
It allows you to move left and right (A & D) on any sized 2D planet,
There aren't any jump mechanics tho.*/
//Gravity Attractor, scrpit attached to the planet:
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);
}
//Gravity Body, script attached to the player:
public GravityAttractor attractor;
private Transform thisTransform;
private Rigidbody2D rb2d;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
thisTransform = transform;
}
void Update ()
{
attractor.Attract (thisTransform);
}
//Player Controller, script attached to the player:
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
}