Hit Box Prioritize layer


(Adam Edney) #1

Quick question, is there a default way get the highest layer entity from a collision point? Because

  world.collidePoint("object", world.mouseX, world.mouseY);

Only get the oldest entity rather than using the layers. I know I can make a method that could search by layer but just wondering if there is a default way of doing so.


(Martí Angelats i Ribera) #2

Why do you want to have the top layer?

Anyways here some code that may help you:

public static function getNearestCollidingEntity(world:World, type:String, x:Number, y:Number):Entity
	var e:Entity;
	var layer:Array;
	var collide:Boolean = false;
	var i:int = world.layerNearest;

	while (!collide && i < world.layerFarthest)
	{
		world.getLayer(i, layer);
		var j:int = 0;
		while (!collide && j < layer.length)
		{
			e = layer[j];
			collide = (e.type == type && e.collidePoint(e.x, e.y, x, y));
			j++;
		}
		i++;
	}
	
	return e;
}

then call

getNearestCollidingEntity(world, "object", world.mouseX, world.mouseY);

(Martí Angelats i Ribera) #3

By the way, if you need to use this you are probably doing something wrong. I can’t think of a real utility for this.


(Adam Edney) #4

Thanks, I will try this tomorrow and get back to you. The reason I want to get highest entity by layer is I’m making a poker game. if I have let’s say 15 cards in my hand they may overlap, so it’s a lot easier to select a card. Am I making sense?


(Jacob Albano) #5

What’s that supposed to mean? I can think of a number of places where this would be useful – particularly in a GUI library. Punk.ui required just such a method to be added to World before it would function correctly.


(Martí Angelats i Ribera) #6

Oh ok. Well so there is the code. XD

Another pull request? :wink:


(Zachary Lewis) #7
public class ClickWorld extends World {
  override public function update():void {
    // After a click...

    // Create a vector and get put colliding entities into it.
    var v:Vector.<Entity> = new Vector.<Entity>();
    collidePointInto("object", mouseX, mouseY, v);

    // If the vector has items, sort it by layer.
    if (v.length > 0) {
      FP.sortBy(v, "layer");

      // The first element is topmost clicked.
      // Do whatever with it.
      v[0].clicked();
    }
  }
}

(Jacob Albano) #8

FP.sortBy() is a function that probably would have saved me from forming a preference for Arrays over Vectors. If only I’d known about it in my youth.


(Martí Angelats i Ribera) #9

I just realized that the quickSort function is not the quikest. Dammit, now i’ll have to improve it…


(Adam Edney) #10

Thanks all for the suggestions. @zachwlewis never new about FP.sortBy(). It would has saved tons of time on my older projects.