Question by
brandonstewartjack · Apr 03, 2020 at 01:25 AM ·
movement2d gametouch controls
How to stop getTouch.position from going through UI buttons?
My mobile game uses each half of the screen to detect touch and moves the player left or right depending on what half of the screen the player touches. The problem is I have a shoot button which triggers the right move since its placed on the right side of the screen. Ive watched tutorials about how to stop UI from interfering with the background but none of them seemed to work (perhaps because getTouch.Position is above the UI?) I really like these controls and wonder if there is a solution to this?
public class playerWalk : MonoBehaviour
{
//variables
public float moveSpeed = 40;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
private float ScreenHeight;
public static bool allowMovement = true;
// Use this for initialization
void Start()
{
ScreenWidth = Screen.width;
ScreenHeight = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (allowMovement == true)
{
int i = 0;
//loop over every touch found
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2 )
{
//move right
RunCharacter(1.0f);
}
else
{
RunCharacter(0);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
//move left
RunCharacter(-1.0f);
}
else
{
RunCharacter(0);
}
++i;
}
}
}
void FixedUpdate()
{
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput)
{
//move player
characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
}
}
Comment