- Home /
Buttons touchscreen movement bug
So my project is this 2D game which is a clone of Space Invaders. I am porting it to android. I did the canvas with 2 buttons of movement (left, right). I am using this script inside an event trigger as Pointer Up and Pointer Down for each button. The right button works perfectly fine, but the left one won't move the player at all.... please help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchControls : MonoBehaviour
{
public float speed = 30;
public GameObject theBullet;
Rigidbody2D rb2D;
private bool left = false;
private bool right = false;
private void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if(left == true)
rb2D.velocity = new Vector2(-1, 0) * speed;
else
rb2D.velocity = new Vector2(-1, 0) * 0;
if (right == true)
rb2D.velocity = new Vector2(1, 0) * speed;
else
rb2D.velocity = new Vector2(1, 0) * 0;
}
public void MoveRight()
{
right = true;
}
public void StopMoveRight()
{
right = false;
}
public void MoveLeft()
{
left = true;
}
public void StopMoveLeft()
{
left = false;
}
public void Shoot()
{
Instantiate(theBullet, transform.position, Quaternion.identity);
soundManager.Instance.playOneShot(soundManager.Instance.BulletFire);
}
}
Answer by highpockets · Aug 19, 2020 at 10:53 PM
The right one works fine because it is the last bool you test. In both cases, you are setting the velocity vector to Vector3.zero if the book equates to false. So, if left is true, you set the velocity and then you cancel it out right afterwards when checking the right bool. On the other hand, if left is false, and right is true, you zero out velocity before you set it to the velocity you want.
To make it work you need to change your logic a bit:
if((!left && !right) || ( left && right))
{
//set velocity to zero
}
else if(left)
{
//set left velocity
}
else if(right)
{
//set right velocity
}
This way if both left and right are true, they cancel each other out and it is the same if they are both false. Yet if one or the other is true, set the velocity accordingly
yep, this worked perfectly for me. thank you so much