Touchscreen Controls Like GetAxis
I am trying to make a 2D game for mobile in which if you press on the left side of the screen the Character goes to the left, and if you press on the right side of the screen the Player goes to the right. How can I make the touch Input feel like Input.GetAxis for the PC. All I can do is make it feel like GetAxisRaw which I do not like.
This is the Code:
if (Input.touchCount > 0) { if (Input.GetTouch(0).position.x < Screen.width / 2) { direction = -1f; } else if (Input.GetTouch(0).position.x > Screen.width / 2) { direction = 1f; } } else { direction = 0f; }
What do you mean "feel like Input.GetAxis"? Do you mean you want the movement to be more smooth?
Answer by Zilppuri · Apr 18, 2017 at 07:21 PM
You should adjust the direction smoothly, relative to the time. You can experiment with Mathf.Lerp for a simple solution on this. More complex solution would have separate "targetDirection" value, and change the direction to that value smoothly over time.
float speed = 3.0f;
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).position.x < Screen.width / 2)
{
direction = Mathf.Lerp(direction, -1, Time.deltaTime * speed);
}
else
{
direction = Mathf.Lerp(direction, 1, Time.deltaTime * speed);
}
}
else
{
direction = Mathf.Lerp(direction, 0, Time.deltaTime * speed);
}
Your answer
Follow this Question
Related Questions
When The Screen Is Touched Jump 0 Answers
[Android] Drag object only in XY plane 0 Answers
Replace touch movement! 0 Answers
Unity Touch Input 0 Answers
DragMouseOrbit for touch screen?? 0 Answers