simple collision detection for edge animate program

620 views Asked by At

I've searched through the similar questions and don't find one that answers my particular situation. I am creating a very basic game in Edge Animate where the player's game piece (a simple rectangle) can move left, right, up and down on the stage, and the player tries to avoid colliding with various other simple rectangles that animate down the stage (along the y-axis) at varying speeds (kind of like a vertical version of Frogger). I can't seem to find a simple collision detection algorithm that works with Edge Animate for detecting when the player's rectangle collides with another rectangle. Here is my code in Edge Animate on the compositionReady action for just two rectangles (trying to get it to alert that the rectangles are colliding:

var object1 = sym.getSymbol("BlueRectangle");
var object2 = sym.getSymbol("RedRectangle");
if (object1.x < object2.x + object2.width  && object1.x +    object1.width  > object2.x &&
    object1.y < object2.y + object2.height && object1.y + object1.height > object2.y) {

// The objects are touching alert("Oops! You crashed!"); setInterval(sym(e), 35);

}

But when I run the program, there is no collision detection. What am I doing wrong? What am I missing? Is there a better way to do this? All of my rectangles will be axis-aligned. Any help would be greatly appreciated.

2

There are 2 answers

0
nurdyguy On

The first thing I would do if I was you was add some debugger lines or console.log(...) to the code so that you can debug it more easily.

I think the error lies in your inequalities being backwards...

If object1 is to left of object2 then object1.x + object1.width < object2.x

If object1 is to right of object 2 then object1.x > object2.x + object2.width

Try that first and check that your left/right collission is working, then check the up/down similarly.

3
userbd On

It looks like you are checking if they are completely overlapping, not colliding. You want to make sure the collision is detected if there is any overlap, not just complete overlap.

In essence, break up detecting overlap with X and Y, change the &&s implying 1 needs to be overlapping with [2] from the left and the right with ||s, wrap it in parenthesis, put an && in between that and a similar statement checking for collisions in y.

Something like this should work, but you need to know where the top, left, right and bottom edges of your objects are (where is x with respect to the object: the left side, the middle, the right? edit: see imgur.com/GE2vVVB)

if ((object1.xright >= object2.xleft || object1.xleft <= object2.xright) && (object1.ytop >= object2.ybottom || object1.ybottom <= object2.ytop))