Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Touchable button

Discussion in 'UGUI & TextMesh Pro' started by barciu, Mar 20, 2017.

  1. barciu

    barciu

    Joined:
    Mar 20, 2017
    Posts:
    8
    I'm creating a single screen 2D game and I want to create mobile touch controls for the player. I'd like an invisible slider/button that would give me the position of the current touch relative to the button's position. In other words, it should work like a horizontal slider that would be able to change it's position based on the user's finger location. I'm not interested in pointer down/pointer up events only, but I need to continuously check the position of the finger. I hope my description is clear enough. Please, help me, because it's my first Unity game and I'm struggling.
     
  2. barciu

    barciu

    Joined:
    Mar 20, 2017
    Posts:
    8
    I ended up adding an empty game object with a RectTransform and then calculating the local click coordinates with the following equation:
    localTouchPosition = touchPosition - transform.position
    then I can use the local position to transform it further into a percentage position:
    percentagePositionX = localPosition.x / rectTransform.rect.width
    percentagePositionY = localPosition.y / rectTransform.rect.height