Reputation: 69
I’m creating a game in HTML5 Canvas that requires an action to execute once one object (a graphic) goes over another object (also a graphic).
I’ve tried methods I’ve seen online, but they don’t seem to work. I was expecting the code to be similar to the Mouseover function, but I’ve tried with this and it did not work.
Is this a possible function? Can it be achieved with graphics?
This was my original code in AS3:
object1.addEventListener( Event.ENTER_FRAME, handleCollision)
function handleCollision( e:Event ):void
{
if (object2.hitTestPoint(object1.x, object1.y, true))
{
// object2 collided with object1
trace("Collision");u
}
}
Upvotes: 0
Views: 290
Reputation: 69
After some research, I have found that collision detection between graphics is not possible in HTML5 for some reason. I have instead used an alternate method where if object2’s co-ordinates are the same as object1’s and the Y-axis is not above it, then the reaction will happen.
Upvotes: 0
Reputation: 333
You have to use BitmapData.hitTest for pixel level detection. This is an argument, so you'd need to have a function like enter_frame to constantly check for overlaps.
Here you can find an example of using BitmapData.hitTest to detect losing contact with a sprite that represents a play area. Your requirement is opposite, to detect contact with another sprite. But it is essentially the same idea.
Hope it helps
Upvotes: 1