johnny 5
johnny 5

Reputation: 21013

Unity how to make a Visual JoyStick in Unity

I'm writing a script to put on a button that will detect a drag direction to move a player

void OnGUI()
{
    if (buttonRect.Contains(Event.current.mousePosition))
    {
        if (Event.current.type == EventType.MouseDown)
        {
            buttonPressed = true;
        }
        if (Event.current.type == EventType.MouseUp)
        {
            buttonPressed = false;
        }
    }
    if (buttonPressed && Event.current.type == EventType.MouseDrag)
    {

    }
}

If this script was to be placed on a button, how could I get the buttons bounds as a rectangle?

Also, If anyone has a better solution for controling movement by drag I would be open for suggestions.

Upvotes: 1

Views: 2256

Answers (2)

renan reis
renan reis

Reputation: 1

If you want a mobile solution that is really accurate and natural like a physical joystick, take a look at this asset:

Ultra Precise D-Pad Joystick

Upvotes: 0

Programmer
Programmer

Reputation: 125445

You can implement your own Visual Joystick by using the Unity new event callback functions such as OnBeginDrag OnDrag and the OnEndDrag function. There is a already made Visual Joystick package out there for Unity, so implementing your own is like reinventing the wheel.

All you have to do is to import the CrossPlatformInputManager package from Unity's UnityStandardAssets then use CrossPlatformInputManager.GetAxis("Horizontal") and CrossPlatformInputManager.GetAxisRaw("Horizontal") to read the direction of the image/thumb.

To make one from scratch, you can flow this video tutorial.

Upvotes: 3

Related Questions