Reputation: 1
I'm trying to create a classical snake game ripoff(im extremely beginner in unity and coding). Game Scene a green floor with a boundaries all made with box. a spare(place holder for snake head) and head/spare keep move forward direction with constant speed.
so i did create a script for snake head for to turn direction when arrow key pressed. in which i tried to rotate snake head by 90 degree when pressing the arrow keys in respective direction.
if (Input.GetKeyDown(KeyCode.LeftArrow) && transform.rotation.y != 90)
{
transform.localEulerAngles = new Vector3(0, -90, 0);
}
if (Input.GetKeyDown(KeyCode.RightArrow) && transform.rotation.y != -90)
{
transform.localEulerAngles = new Vector3(0, 90, 0);
}
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.rotation.y != 180)
{
transform.localEulerAngles = new Vector3(0, 0, 0);
}
if (Input.GetKeyDown(KeyCode.DownArrow) && transform.rotation.y != 0)
{
transform.localEulerAngles = new Vector3(0, 180, 0);
}
Problem the problem is in the second part of the every if statement i.e. transform.rotation.y != 90. for example .i pressed left arrow key and snake head direction toward right direction. this line suppose to stop the direction change of head in this type of condition. any idea how can i fix this.
Upvotes: 0
Views: 69
Reputation: 90891
In general
Quaternion
has not 3 but rather 4 components x
, y
, z
, w
which represent a complex number and all move in the range -1
to 1
.
Unless you know exactly what you are doing you never directly touch those components.
To answer the title how to compare the directions - you can either e.g. go for Quaternion.Angle
or go Vector based and rather compare e.g. Vector3.forward
to transform.forward
via Vector3.SignedAngle
.
To answer your issue: As was suggested rather store the last assigned direction like e.g.
private enum Direction
{
Up, // or Forward
Down, // or Backward
Left,
Right
}
private Dictionary<Direction, Vector3> directionAngles = new ()
{
{Direction.Up = Quaternion.Euler(0, 0, 0)},
{Direction.Down = Quaternion.Euler(0, 180, 0)},
{Direction.Left = Quaternion.Euler(0, -90, 0)},
{Direction.Right = Quaternion.Euler(0, 90, 0)},
}
private Direction currentDirection;
and then do e.g.
if (Input.GetKeyDown(KeyCode.LeftArrow) && currentDirection != Direction.Right)
{
currentDirection = Direction.Left;
} else if (Input.GetKeyDown(KeyCode.RightArrow) && currentDirection != Direction.Left)
{
currentDirection = Direction.Right;
} else if (Input.GetKeyDown(KeyCode.UpArrow) && currentDirection != Direction.Down)
{
currentDirection = Direction.Up;
} else if (Input.GetKeyDown(KeyCode.DownArrow) && currentDirection != Direction.Up)
{
currentDirection = Direction.Down;
}
transform.localEulerAngles = directionAngles[currentDirection];
Upvotes: 0