Player gets stuck at position.

Hi guys!

I just downloaded Unity a week ago so I am very much of a newbie… Anyways, I am making a game where the player moves on the x axis and you can change his direction by pressing space. I want him to stop at the edge of the screen and if space is pressed again, move in the opposite direction. For some reason though, once he hits the edge of screen he gets stuck there no matter how many times do I press space… Please help me guys!!!:frowning:

Here is the script for the player:

#pragma strict
    
    var speed = 0.03;
    var key : KeyCode;
    var isMoving = true;
    
    
    
    function Update ()
    {
    	if(isMoving == true)
    	{
    	transform.Translate(Vector3.left * speed);
    	}
    
    	if(Input.GetKeyDown(key))
    	{
    	isMoving = true;
    	speed *= -1;
    	
    	}
    
    	if(transform.position.x < -2.74)
    	{
    	isMoving = false;
    	}
    	
    	if(transform.position.x > 2.74)
    	{
    	isMoving = false;
    	}
    
    }

Thanks!!!

What is happening is this:

When your player reaches +/- 2.74, the isMoving variable is set to false.

Then, whenever you press space, isMoving is set to true again, and speed is multiplied by -1. BUT, before the player actually moves, the check for wheter the player is at +/- 2.74 fires again, and isMoving gets put back to false before you move the player.

The fix is to put the movement block AFTER the check for space input, and BEFORE the check for if you are on the edge of the map.

When you press space you set the var isMoving = true; in the 2nd if statement. However before that variable reaches the 1st if statement(the one that makes the player move) it needs to finish the rest of the code. Because your players position is still > 2.74, var isMoving gets set back to false immediatly (4th if statement), and when the update function is called again… var isMoving is = false and your player will not move.

its an easy fix. swap the 1st if statement with the second one like this:

#pragma strict
 
    var speed = 0.03;
    var key : KeyCode;
    var isMoving = true;
 
 
 
function Update ()
{

  if(Input.GetKeyDown(key))
    {
    isMoving = true; // variable is set to true
    speed *= -1;
 
    }

    if(isMoving == true) //look its true! lets execute the code
    {
    transform.Translate(Vector3.left * speed);
    }
 
    if(transform.position.x < -2.74)
    {
    isMoving = false;
    }
 
    if(transform.position.x > 2.74)
    {
    isMoving = false;
    }
 
}

Thank you guys! I actually realized the same thing this morning but did not know how to solve it. Thank you very much!!