Reputation: 1350
I am using Corona SDK to detect collisions. I have no problem detecting whether the collision was to the left of the square or to the right using the following code:
if (event.other.x < displayObj.x)
the collision code:
function box:collision(event)
if event.phase == "ended" then
if event.other.id and event.other.id == "c" then
--need to detect top collision
test = 1
end
How do I detect whether the top of the square has collided with something?
Upvotes: 0
Views: 291
Reputation: 3406
You can use linear algebra! Vectors and the dot product are very useful for figuring out what you want. You can find more indepth information if you google: Half-space test dot product
Assuming you have a box named A
and collision point B
, with positions (A.x,A.y)
and (B.x,B.y)
and the forward direction of the box determined by (A.dirX, A.dirY)
you can determine if point B is in front or behind box A's direction like this:
Get a vector from position A to B and normalize it:
vectorToBNormalized = normalize((B.x,B.y)-(A.x,A.y))
Use the dot product of vectorToBNormalized
and A
's forward vector to determine if B is in front of behind.
result = dot(vectorToBNormalized, normalize(A.dirX, A.dirY))
If the result is less than 0 then: B is behind A; If the result is greater than 0 then: B is in front of A.
To find out if the box B is left or right of box A, repeat the process but using a right-facing vector instead of a forward vector for box A. For example, if up is defined by (0, 1)
, then right would be (1, 0)
.
This way you can determine if the point of collision is behind/infront, or left/right.
Upvotes: 1