2
\$\begingroup\$

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?

\$\endgroup\$

3 Answers 3

4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I would say that all but the most exotic objects your center-to-center calculation should be okay. \$\endgroup\$ May 13, 2011 at 14:11
3
\$\begingroup\$

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.

hitTestPoint

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$
    – tmsimont
    Jul 14, 2011 at 4:29
  • \$\begingroup\$ 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/… \$\endgroup\$
    – Valkea
    Jul 14, 2011 at 13:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .