Handle going out of circle limiter (Multitouch solution)

I am creating joystick on TouchPhase.Began, and then I am moving the handle on TouchPhase.Moved.

Can’t access direction, horizontal nor vertical from the joystick script since they are read only
(Joystick Pack | Input Management | Unity Asset Store)

So I am trying to do it manually:

           else if (t.phase == TouchPhase.Moved)
            {
              touchLocation thisTouch = touches.Find(touchLocation => touchLocation.touchId == t.fingerId);
              thisTouch.handle.position = getTouchPosition(t.position);

              Vector2 direction = ((thisTouch.handle.localPosition - thisTouch.handle.localPosition * 0f).normalized);
          
            }

Semi works, problem is that handle can go out of the circle limiter and even slight movement will move the player, is this even right way to do it?

I tried doing something like this:
thisTouch.handle.localPosition = (getTouchPosition(t.position) - (Vector2)thisTouch.handle.position).normalized;

Can I somehow convert touch into actual click and move instead of doing workaround like this?

I would like to use dead zone and handle range variables, otherwise I have to do everything in script, for example this is my idea of dead zone:

         float horizontal, vertical;
                if (direction.x >= 0.2f || direction.x <= -0.2f)
                {
                    horizontal = direction.x;
                }
                else horizontal = 0f;

                if (direction.y >= 0.2f || direction.y <= -0.2f)
                {
                    vertical = direction.y;
                }
                else vertical = 0f;

                core1.direction = new Vector2(horizontal, vertical);

You’re welcome to look at how I did it in my proximity_buttons class, which has a VAButton class, which is my “Virtual Analog Button,” basically a 2D joystick. You can put as many of them on the screen as you like at once, and each one gets temporarily “owned” by whatever finger touches them first, as you would expect.

proximity_buttons is presently hosted at these locations:

https://bitbucket.org/kurtdekker/proximity_buttons

https://github.com/kurtdekker/proximity_buttons

The DemoTwinStickShooter scene will run them so you can see how the code in them works.

If you turn on the .doNormalize boolean it will constrain the output to a unit circle. The way the code is now, the actual visual blip of your finger still moves around in a rectangle, as that clamping is done in another place. But you can see how it’s done in the VAButton and reorganize it if you like.

1 Like