- Home /
how can I make a 2d player face the direction it is moving?
Hello I am highly confused because i am trying to make my character face the direction it is moving (can face up, down, left, right, and all the diagonals) this is my code for my player
using UnityEngine;
/// <summary>
/// Player controller and behavior
/// </summary>
public class PlayerScript : MonoBehaviour
{
/// <summary>
/// 1 - The speed of the ship
/// </summary>
public Vector2 speed = new Vector2(50, 50);
// 2 - Store the movement and the component
private Vector2 movement;
private Rigidbody2D rigidbodyComponent;
void Update()
{
// 3 - Retrieve axis information
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
// 4 - Movement per direction
movement = new Vector2(
speed.x * inputX,
speed.y * inputY);
}
void FixedUpdate () {
Vector2 moveDirection = GameObject.rigidbody2D.velocity;
if (moveDirection != Vector2.zero) {
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
and i keep getting the error " error CS0120: An object reference is required to access non-static member `UnityEngine.GameObject.rigidbody2D' " if you know how i can fix this and make my player face the direction its moving please help, Thanks in advance
P.S: I would normally add smiley faces but i don't think i can add them P.P.S: I am also new to this so a detailed explanation would be helpful... Thanks.
Answer by goutham12 · Oct 09, 2017 at 07:10 AM
First rigidbody2D you should not use this. it's absolute function. take the reference like Rigidbody body; void Start(){ body = getcomponent(); }
now use like Vector2 moveDirection = body.velocity;
and one more this there is lot of scripts in internet to control the player. just search you ill find the better one.