# Actionscript 3: Which side of object is hit?

I have a two objects colliding with each other. I am testing for the collision with if(ob1.hitTestObject(ob2)){//do something }. Is there a way to determine which side of the object was hit, i.e. if ob2 is a square, which side of the square was collided with?

The hitTest method provided by flash won't give you such an information.

If you have two squares, you can simply calculate the vector between their center-points and use that to determine the side. For arbitrarily shaped objects, this won't work though.

Another option is to have "sensor" points on your object, eg. top, left, right, bottom, and do a hit-test for each of these points against the other shape.

• I would say that all but the most exotic objects your center-to-center calculation should be okay. – edA-qa mort-ora-y May 13 '11 at 14:11

What the .hitTestObject() function does is compare the position and transformation of objects to see if the object's bounding boxes overlap at all. If you require more precise collision than that, it is usually better to test for collision between an object and various points on the other object using the .hitTestPoint function.

For example in your scenario you take collision with certain points to mean that the object has collided against a certain side of the object.

In 2D you can know which side of a segment is a point using the signed area of a triangle.

Let :

• P any point to test against the segment

• AB the segment formed by points A & B.

SignedArea = (Bx-Ax) * (Py-Ay) - (Px-Ax) * (By-Ay);


The SignedArea will be positive if ABP are oriented counterclockwise around the triangle, and negative if oriented clockwise.

Thus,

• if SignedArea is positive, the point P is on the LEFT side of the segment AB (seen from A to B)

• if SignedArea is negative, the point P is on the RIGHT side of the segment AB (seen from A to B)

• if SignedArea is 0, the point P is on somewhere one the "line" (not necessarily the segment)

In 3D you can know which side of a surface is a point using dot product and cross product. But as I guess your problem is a 2D problem, this should not be required.

• 4 sides of square doesn't mean more than 2 dimensions... this solution only addresses collision with a line, not a square. How can one identify which side of a square (top,left,bottom,right) was hit by the moving object? – tmsimont Jul 14 '11 at 4:29
• There is no doubt that this answer wasn't the best one I wrote. But the following "question/answers" should give you some more (useful?) informations: gamedev.stackexchange.com/questions/13080/… – Valkea Jul 14 '11 at 13:54