Hello!
I’m new to unity and have some questions for you guys.
I’m creating a 2d game in which you move a rabbit between 3 lanes in order to avoid falling blocks. I already have a character with animation and collision standing on a sprite with a box collider that acts as ground.
So basically i would like to know how to move my rabbit left and right between 3 points using arrow keys.
I found plenty of tutorials online in how to make a character move around, but nothing regarding this.
Or maybe i just don’t know what to google.
Here’s a picture to further illustrate my problem since my english isn’t the best.
You can do something like this:
public Vector3 leftPos;
public Vector3 rightPos;
public Vector3 centralPos;
void Start()
{
//Start in the center position
transform.position = centralPos;
}
void Update()
{
//move to the correct position
var posToMove = DeterminePos(transform.position);
if (posToMove != null)
transform.position = (Vector3)posToMove;
}
private Vector3? DeterminePos(Vector3 pos)
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
//check if we are in the outer left
if (transform.position == leftPos)
return leftPos; //return same position because we don't need to move
if (transform.position == centralPos)
return leftPos; //we want to move to the outer left position
if (transform.position == rightPos)
return centralPos; //we want to move to the center position
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
//check if we are in the outer left
if (transform.position == rightPos)
return rightPos; //return same position because we don't need to move
if (transform.position == centralPos)
return rightPos; //we want to move to the outer right position
if (transform.position == leftPos)
return centralPos; //we want to move to the center position
}
return null; //default
}