Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Detecting when an entity is tapped or clicked

Discussion in 'Project Tiny' started by Grillbrick, Mar 9, 2019.

  1. Grillbrick

    Grillbrick

    Joined:
    Jul 17, 2015
    Posts:
    9
    So I figured out I can get the position of a tap/click using
    Code (JavaScript):
    1. ut.Runtime.Input.getInputPosition()
    but how do I tell if this is inside an entity? Do I need to add physics, or can I use a HitBox2D? I can get the x and y position of the entity, but do I just need to hard code the numbers for width and height, or can I access the width and height of the sprite somehow?
     
  2. Zoelovezle

    Zoelovezle

    Joined:
    Aug 7, 2015
    Posts:
    54
  3. Rupture13

    Rupture13

    Joined:
    Apr 12, 2016
    Posts:
    131
    You don't have to hardcode numbers, but you do indeed need a HitBox2D.
    Also you probably want to get your inputposition in worldspace instead of something else, so you want to do something like
    ut.Core2D.Input.getWorldInputPosition(this.world)
    to get that instead of
    ut.Runtime.Input.getInputPosition()
    .

    Answer to a previous similar question:
    1. Firstly, for a sprite2D to be able to be clicked, it needs the Sprite2DRendererHitBox2D component
    2. Then you have to detect your click or mouseDown
    3. Then you have to get the world-space point of clicking
    4. Then you have to raycast (or equivalent) to your world-space point of clicking
    5. Maybe do some additional checks to see if the entity you hit is the one you want to hit
    In code (assuming you have the Sprite2DRendererHitBox2D component set on your entity), it would look something like this:

    Code (CSharp):
    1. if (ut.Core2D.Input.getMouseButtonDown(0)) {
    2.     let mousePos = ut.Core2D.Input.getWorldInputPosition(this.world);
    3.     let hit = ut.HitBox2D.HitBox2DService.hitTest(this.world, mousePos, this.world.GetEntityByName("Camera");
    4.  
    5.     if(!hit.entityHit.isNone() && this.world.getEntityName(hit.entityHit) == "MyEntity") {
    6.         //Do something with the hit entity
    7.     }
    8. }
    Note that for better code, you probably want to store a reference to your camera entity instead of finding it by name. Same goes for identifying your hit entity by name.
     
    Jalol and Grillbrick like this.
  4. Grillbrick

    Grillbrick

    Joined:
    Jul 17, 2015
    Posts:
    9
    Awesome - that did it. Thank you!