Unity how to make a Visual JoyStick in Unity

2019-01-01 11:15发布

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.

标签: c# unity3d
1条回答
无与为乐者.
2楼-- · 2019-01-01 12:21

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.

查看更多
登录 后发表回答