| 63 | } |
| 64 | |
| 65 | void Ball::collideWithPaddle(Paddle* paddle) |
| 66 | { |
| 67 | auto paddleRect = paddle->getRect(); |
| 68 | paddleRect.origin.x += paddle->getPosition().x; |
| 69 | paddleRect.origin.y += paddle->getPosition().y; |
| 70 | |
| 71 | float lowY = paddleRect.getMinY(); |
| 72 | float midY = paddleRect.getMidY(); |
| 73 | float highY = paddleRect.getMaxY(); |
| 74 | |
| 75 | float leftX = paddleRect.getMinX(); |
| 76 | float rightX = paddleRect.getMaxX(); |
| 77 | |
| 78 | if (getPosition().x > leftX && getPosition().x < rightX) |
| 79 | { |
| 80 | |
| 81 | bool hit = false; |
| 82 | float angleOffset = 0.0f; |
| 83 | |
| 84 | if (getPosition().y > midY && getPosition().y <= highY + radius()) |
| 85 | { |
| 86 | setPosition(getPosition().x, highY + radius()); |
| 87 | hit = true; |
| 88 | angleOffset = (float)M_PI / 2; |
| 89 | } |
| 90 | else if (getPosition().y < midY && getPosition().y >= lowY - radius()) |
| 91 | { |
| 92 | setPosition(getPosition().x, lowY - radius()); |
| 93 | hit = true; |
| 94 | angleOffset = -(float)M_PI / 2; |
| 95 | } |
| 96 | |
| 97 | if (hit) |
| 98 | { |
| 99 | float hitAngle = (paddle->getPosition() - getPosition()).getAngle() + angleOffset; |
| 100 | |
| 101 | float scalarVelocity = _velocity.getLength() * 1.05f; |
| 102 | float velocityAngle = -_velocity.getAngle() + 0.5f * hitAngle; |
| 103 | |
| 104 | _velocity = Vec2::forAngle(velocityAngle) * scalarVelocity; |
| 105 | } |
| 106 | } |
| 107 | } |