Tibix
Tibix

Reputation: 390

Collision in Canvas with Rectangles

I Made a Pen where i have a function Rectangle() that creates a Rectangle and handles collision with the created Object.

But i can only get two of the Sides to work (Top and Left), the others work like reversed and pull the Sphere in on collision instead of bouncing them off, somehow i cannot figure out how to fix this.

I have been playing around with the Logic for hours now, this is the current code:

// Top
if (bp.y > posY - brd && bp.y < yy + brd && bp.x > posX && bp.x < xx) {
    ball.velocity.y *= ball.restitution;
    ball.position.y = posY - brd;
}
// Bottom
if (bp.y > yy + brd && bp.y < posY - brd && bp.x > posX && bp.x < xx) {
    ball.velocity.y *= ball.restitution;
    ball.position.y = yy + brd;
}
// Left
if (bp.x > posX - brd && bp.x < xx + brd && bp.y > posY && bp.y < yy) {
    ball.velocity.x *= ball.restitution;
    ball.position.x = posX - brd;
}
// Right
if (bp.x > xx + brd && bp.x < posX - brd && bp.y > posY && bp.y < yy) {
    ball.velocity.x *= ball.restitution;
    ball.position.x = xx + brd;
}

On Line 116 you will find the Variables so you dont get confused by the condition.

Upvotes: 0

Views: 49

Answers (1)

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

Reputation: 4116

Try this:

// Top
if (bp.y > posY - brd && bp.y < posY && bp.x > posX && bp.x < xx) {
    ball.velocity.y *= ball.restitution;
    ball.position.y = posY - brd;
}
// Bottom
if (bp.y < yy + brd && bp.y > yy && bp.x > posX && bp.x < xx) {
    ball.velocity.y *= ball.restitution;
    ball.position.y = yy + brd;
}
// Left
if (bp.x > posX - brd && bp.x < posX && bp.y > posY && bp.y < yy) {
    ball.velocity.x *= ball.restitution;
    ball.position.x = posX - brd;
}
// Right
if (bp.x < xx + brd && bp.x > xx && bp.y > posY && bp.y < yy) {
    ball.velocity.x *= ball.restitution;
    ball.position.x = xx + brd;
}

Summary: in the bottom and right checks, I flipped the operator in the first clause, and changed the right operand in the second.

Upvotes: 1

Related Questions