- Home /
Touch input not working well for mobile game made with Unity 2D.
I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9+), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related.
This is the code attached to the player:
void FixedUpdate()
{
Jump();
Dead();
}
void Jump()
{
if (Input.touchCount > 0 && isGrounded)
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce * Time.fixedDeltaTime), ForceMode2D.Impulse);
}
}
Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.
Answer by WaqasHaiderDev · May 31, 2020 at 10:37 AM
Hi, are you using Unity Remote to test the game? On Unity Remote the game looks blurry as well as laggy because it is just casting the computer screen to the mobile and is not directly running game on mobile. Regarding touch missing, I am not sure what is causing it but what I see some things which does not look correct to me. Instead of calling Jump function in Fixed Update, try to take user input in Update method. Because fixed update will run each 0.02 seconds and it will miss the user input in between. But in Update method, it runs more frequently. May be this is the reason for your input missing sometimes. This should be case with keyboard input also by the way. But still, if the problem is something else, you should modify your code as below
bool jump = false;
void Update()
{
if (Input.touchCount > 0 && isGrounded)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
jump = true;
}
}
}
void FixedUpdate()
{
if(jump == true)
{
jump = false;
Jump();
}
}
void Jump()
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
Also check that I have removed Time.fixedDeltaTime because FixedUpdated will always call at fixed interval and does not depend on frame rate of mobile. Time.deltaTime is used in Update because frames are not updated equally on all mobiles and depend on FPS so we make things multiply with Time.deltatime but this is not the case with FixedUpdate.