Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: Map Input.GetButtonDown("Jump") in iOS touch

Tags:

c#

mono

unity3d

In Unity, I can use Input.GetButtonDown("Jump") to get obtain the key Space by default. How can I map screen touch to the "Jump" action in iOS?

In this documentation, it explains only obtaining touches in JavaScript. While in this video tutorial, it only mentions about Button. Is there a way to directly map screen touch/ gesture to a pre-defined action (like Jump) ?

Note: I use mono C# script.

like image 754
Raptor Avatar asked Jan 11 '23 11:01

Raptor


1 Answers

There are more than one way to get Touch evens in unity:

if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
    //Your stuff here
}

The above demonstrates using Input.GetTouch

However, there's an alternative, which I tend to prefer:

if(Input.GetMouseButtonDown(0))
{
    //Your stuff here
}

or

if(Input.GetMouseButtonUp(0))
{
    //Your stuff here
}

The above use Input.GetMouseButtonDown and Input.GetMouseButtonUp respectively, which not only trigger on the left mouse click, but also trigger on touch events for iOS and Android. As suggested by the names, GetMouseButtonDown triggers when you first touch the screen and GetMouseButtonUp triggers when your finger releases. You'll obviously want to add some extra checks in there, for example to make sure the user isn't trying to drag something, or if he's keeping his finger pressed on the screen etc.

However keep in mind that the above will trigger no matter where you click, so long as the script containing them is active. So if your game has buttons as well (which I'm guessing it will), you could either check if the click/touch is in a certain region, or you could add a transparent plane in front of the camera and behind your buttons, then check for clicks like this:

if(Input.GetMouseButtonDown(0))
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if(Physics.Raycast(ray,out hit) && hit.collider.gameObject.name == "myObjectName")
    {
        //Your stuff here
    }
}

The above will only trigger if you left click over a gameObject with a name you choose (which also has a collider) and there's nothing else between it and the camera. A transparent plane will catch all your clicks, allowing you to stick other elements above it.

If I haven't explained something well enough, or you have any other questions, lemme know and I'll try to elaborate.

like image 69
Steven Mills Avatar answered Jan 19 '23 16:01

Steven Mills