How to create touch controls depending on the touch position?

Hey,

I need help creating touch controls for my jumper game. The controls are supposed to work like the ones you see right here, but I’m only interested in the left two zones, controling the movement.
When you tap e.g. the zone for walking left, the character moves left (of course), but the one thing that is special about those controls is, that if you move your finger to the right zone, then the character starts to move right. You do not have to stop and start touching like you’d have to with the basic Unity buttons! How do i code this in Unity?

Greetings, Eliah

@eliahlohr -

You can do it many ways.

Use Input.touch and measure where you tapped on screen coordinates. Just check where you are to define areas and you can do the sliding similarly, just change the values based on L / R button area…

Using EventTrigger component or implementing UI event listener interfaces as they are doesn’t help much, as they don’t detect clicks or drags that began outside of button.

There are some workarounds but I don’t remember right now…This has been discussed on the forums IIRC. You can at least use screen or canvas covering (might not cover screen but controls area) clear (transparent image) rectTransforms to catch clicks… This way your clicks will never start “outside” of UI RectTransforms. Regarding this - also check ExecuteEvents class, and UI raycasting classes.

However, it might still be easiest to just capture clicks on Update loop, and then process them (where and what was clicked?) each and every frame, since it won’t be too taxing for Unity. In this case you might do just something like this (of course, there is no must to use UI system elements):

RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, Input.mousePosition, null, out position);

After this, just pure “math”, what area you hit is the direction of your stick. Naturally, swap the Input.mousePosition with touch if you want.