move bug - Missing condition

Hi guys, I’ve written a code that moves the player left or right if you touch the left or right side of the screen but I have a small problem.

When I hold down the left side of the screen and move my finger to the right side and release it, moveLeft remains true and the player keeps moving left. I know it’s a condition problem but I can’t find it, I feel so stupid because it seems so easy.

Touch touch = Input.GetTouch(i);
if(touch.position.x < Screen.width/2)
{
	if(touch.phase == TouchPhase.Began)
		moveLeft = true;

	if(touch.phase == TouchPhase.Ended)
		moveLeft = false;
}
if(touch.position.x > Screen.width/2)
{
	if(touch.phase == TouchPhase.Began)
		moveRight = true;

	if(touch.phase == TouchPhase.Ended)
		moveRight = false;
}

What can I do to prevent that effect ? Thanks for reading.

The reason why your code does not work is because when you release your finger it does actions, defined for another end of screen. I.e. if you pressed left side, it sets moveLeft to true, but when you release it makes:

if(touch.position.x > Screen.width/2)
{
    if(touch.phase == TouchPhase.Began)
        moveRight = true;
 
    if(touch.phase == TouchPhase.Ended)
        moveRight = false;
}

And moveRight is already set to false.

Found it ! It was as simple as adding these lines at the end :

if(Input.touchCount > 0)
...

else
{
   moveRight = moveLeft = false;
}

Thanks anyway for trying to help me out ! :slight_smile: