I’m making my first mobile game and I don’t understand how getting touch input works. I tried looking at the scripting API and some other forum posts but I can’t figure it out. What I need to happen is when the player touches the screen the player will jump; But only when you tap, if the screen is held down by a touch input nothing will happen.
Here’s my current code, I already know this won’t work because when the player touches the screen the ‘touchCount’ will go up to 1 and the ‘AddForce’ stuff will be called every frame, rather than once.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float speed;
public float jumpForce;
void Awake ()
{
// Controls the players constant movement forward
rb.AddForce (speed, 0, 0, ForceMode.VelocityChange);
}
void Update ()
{
if (Input.GetMouseButtonDown (0) || Input.touchCount > 0)
{
rb.AddForce (0, jumpForce, 0, ForceMode.Impulse);
}
}
}
What do you mean by second condition? I’m not exactly sure what part you’re talking about. And no, I do not need multi touch for anything else in my game; Everything is just checking for if the screen was tapped
You just have to add a bool or some other check condition. So, if it’s jumping. then when you tap, you set the bool to true. Then in the update you also check if the bool is true before you try to add force. You’ll then need to determine when a player has landed to turn the bool back to false.
Also note you can check “stages” of touches and just see if the touch is in the began stage, however a player could tap over and over to keep jumping if you do it that way.
Thanks but i’m running into a strange ‘glitch’ I guess? Currently I have the ‘jumpForce’ set to a low value so the player does not jump very high. When I click and jump on the PC it does not go very high, but when I tap on mobile it goes ~5 times as high. Can you explain why this might be happening?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody rb;
public float speed;
public float jumpForce;
void Awake ()
{
// Controls the players constant movement forward
//rb.AddForce (speed, 0, 0, ForceMode.VelocityChange);
}
void Update ()
{
// Mobile touch input detection
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch (0);
switch (touch.phase)
{
case TouchPhase.Began:
rb.AddForce (0, jumpForce, 0, ForceMode.Impulse);
break;
}
}
// PC debug code (remove later)
if (Input.GetMouseButtonDown (0))
{
rb.AddForce (0, jumpForce, 0, ForceMode.Impulse);
}
}
}
No. As far as understanding goes, you can assume mouse input defaults to being the first touchpoint on mobile. IMO there really isn’t much reason to delve into touch-input unless you need to make use of multi-touch.