Jump to content

How to allow touchstart events to fire from multiple display objects?


cammil
 Share

Recommended Posts

Setup:

  1. There are multiple display objects which are at the same level on the scene hierarchy graph.
  2. These display objects have overlapping hit areas (e.g. they are near each other and/or the hit areas are large)
  3. The user touches the area where the hit areas intersect

It seems that pixi will trigger the touchstart event on only one of these display objects. How do I get the event to fire on both?

My Goal:

I have multiple objects which the user can drag around the scene. However, I want to allow the user to be quite inaccurate with their finger, so that if they attempt to drag an object which is near, AND there is no object directly underneath their finger, that object will be picked up successfully. If there are multiple object near the event, then the closest one should be picked up. This is the motivation for the above question.

Link to comment
Share on other sites

I have done a similar solution by having listening for touchstart only on my main container and set the children to be false. Then I just iterate through the list of items I know should have interaction and check if they contain the point of the touch.

Basically your problem could be solved with something like this:

 

function findHit(point){
  var closest = null;
  var hits = [];
  var distance = 4294967296; //Or something else that is large
  for(var i =0; i < objects.length; i++){
     var object = objects[i];
     var bounds = object.getBounds();
     var centerX = bounds.x + bounds.width/2;
     var centerY = bounds.y + bounds.height/2;
     var dx = centerX - point.x;
     var dy = centerY - point.y;
     var dist = dx*dx + dy*dy; //Distance is not squared as it's not needed.
     if(dist < distance){
       closest = object;
       distance = dist;
     }
     if(object.containsPoint(point)){
       hits.push({ distance: dist, object: object});
     }
  }

  hits.sort( function(a,b){ return a.distance - b.distance;});
  
  if(hits.length > 0)
    return hits[0];
  else
    return closest;
}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...