- Home /
Moving player between pre-determined points
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. https://up.ppy.sh/files/721341236123145.png
Answer by ShadyProductions · May 29, 2017 at 08:44 PM
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
 }
you might wanna add a kind of lerp to this solution, i guess. i think it would "warp" the character between the lanes like this, right?
Yes it will practically just teleport the character between the lanes.
Looks like a solid plan, however i was thinking of having movement animation so i assume warping wont work there? Someone suggested on the forums adding 3 trigger on the ground that stop all movement, and then setting the velocity of the rigidbody to move with the right speed & in the desired direction until it collides with the trigger.
I think i'll try that out first, even though i have no idea how to script it yet. :p
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                