- Home /
Moving character on android using touch
So I'm fairly new to using unity and have been trying to learn. I'm just trying to have the player move left and right based on the side of the screen the player touches. For some reason though he only moves to the right. Not sure if it has to do with the h.position logic but that's my best guess as I'm not entirely sure what value that produces. Any help would be appreciated.
void PlayerWalkMobile() { float force = 0.0f; float velocity = Mathf.Abs(rb.velocity.x); if(Input.touchCount > 0) { Touch h = Input.touches[0]; Vector2 position = Camera.main.ScreenToWorldPoint(new Vector2(h.position.x, h.position.y)); if (h.position.x > 0) { if (velocity < maxVelocity) force = speed; Vector3 scale = transform.localScale; scale.x = 1; transform.localScale = scale; PlayerAnimate.SetInteger("Walk", 1); } else if (h.position.x < 0) { if (velocity < maxVelocity) force = -speed; Vector3 scale = transform.localScale; scale.x = -1; transform.localScale = scale; PlayerAnimate.SetInteger("Walk", 1); } rb.AddForce(new Vector2(force, 0)); if(h.phase == TouchPhase.Ended) { PlayerAnimate.SetInteger("Walk", 0); } } }
,So I'm fairly new to using unity and have been trying to learn. I'm just trying to have the player move left and right based on the side of the screen the player touches. For some reason though he only moves to the right. Not sure if it has to do with the h.position logic but that's my best guess as I'm not entirely sure what value that produces. Any help would be appreciated.
void PlayerWalkMobile() { float force = 0.0f; float velocity = Mathf.Abs(rb.velocity.x); if(Input.touchCount > 0) { Touch h = Input.touches[0]; Vector2 position = Camera.main.ScreenToWorldPoint(new Vector2(h.position.x, h.position.y)); if (h.position.x > 0) { if (velocity < maxVelocity) force = speed; Vector3 scale = transform.localScale; scale.x = 1; transform.localScale = scale; PlayerAnimate.SetInteger("Walk", 1); } else if (h.position.x < 0) { if (velocity < maxVelocity) force = -speed; Vector3 scale = transform.localScale; scale.x = -1; transform.localScale = scale; PlayerAnimate.SetInteger("Walk", 1); } rb.AddForce(new Vector2(force, 0)); if(h.phase == TouchPhase.Ended) { PlayerAnimate.SetInteger("Walk", 0); } } }
Answer by xxmariofer · Jan 30, 2019 at 08:28 AM
Hello h.position.x cannt be less than zero since it starts at 0 so the else if will never be entered. you can change it to something like this
if (touch.position.x > (Screen.width/2)) {
Your answer
![](https://koobas.hobune.stream/wayback/20220612190742im_/https://answers.unity.com/themes/thub/images/avi.jpg)