简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM