'Make player movement consistent with touch controls?
Currently I'm using this code for player movement for my very basic mobile game.
if (Input.touchCount > 0)
{
//Animation
animator.SetBool("Is Moving", true);
//Left click
var touch = Input.GetTouch(0);
if (touch.position.x < Screen.width / 2)
{
transform.position += new Vector3(-1, 0, 0) * Time.deltaTime * speed;
transform.rotation = Quaternion.Euler(Vector3.up * 180); //Sets rotation of character
}
//Right Click
else if (touch.position.x > Screen.width / 2)
{
transform.position += new Vector3(1, 0, 0) * Time.deltaTime * speed;
transform.rotation = Quaternion.Euler(Vector3.up * 0); //Sets rotation of character
}
if (Input.touchCount > 1 && !isJumping)
{
transform.position += new Vector3(0, 5, 0) * Time.deltaTime;
isJumping = true;
}
}
The problem I'm faced with is this: currently, when touching with more than 1 finger, sometimes the player will move in the direction of the later finger to be touched down, and sometimes it doesn't (so if I'm holding down left, and then hold down right, sometimes the player will continue to move left, sometimes the player will instead move right).
I'm not sure what is causing the inconsistency, any insight would be appreciated.
Solution 1:[1]
You could keep track of that last known direction using an enum, and if if at any point there are no touches set it to none. If at anypoint you have a left and right touch you can resort to the last known direction if it is not none.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | acornTime |
