- Home /
rotate 2d object toward movement
Hello all,
I'm building a simple 2d snake game and I'm trying to figure out how to move the "head" of the snake on Input without messing with the inputs directions
this is the script. It says that the snake first moves left and then according to the inputs. once I've tries changing rotation of the transform it didn't work and also Mathf.Atan2 didn't work for me...
I realize this is a very common question... Script:
public class SnakePlayer : MonoBehaviour {
Vector2 dir = Vector2.left;
void Start ()
{
InvokeRepeating("MoveSnake", 0.6f, 0.6f);
}
void Update () {
if (Input.GetKey(KeyCode.RightArrow))
{
dir = Vector2.right;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
dir = -Vector2.up;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
dir = -Vector2.right;
}
else if (Input.GetKey(KeyCode.UpArrow))
{
dir = Vector2.up;
}
}
void MoveSnake()
{
transform.Translate(dir);
}
}
Answer by Eco-Editor · Apr 26, 2018 at 05:23 PM
This is how I've solved it so far...
void Update () {
if (Input.GetKey(KeyCode.RightArrow))
{
transform.eulerAngles = new Vector3(0, 0, 180);
dir = -Vector2.right;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
transform.eulerAngles = new Vector3(0, 0, 90);
dir = -Vector2.right;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
transform.eulerAngles = new Vector3(0, 0, 0);
dir = -Vector2.right;
}
else if (Input.GetKey(KeyCode.UpArrow))
{
transform.eulerAngles = new Vector3(0, 0, -90);
dir = -Vector2.right;
}
}
Your answer
Follow this Question
Related Questions
Rotate object towards velocity? 1 Answer
How can I rotate my player to look at the direction my Joystick is pointing to? (Top-Down 2D) 3 Answers
Quaternion Rotate Towards Y Value 1 Answer
Problem when rotating sprite and moving it foward 1 Answer
How to make plane rotate towards player and keep upright? 1 Answer