Last active
August 29, 2015 14:24
-
-
Save nitzel/d6cbb23dfe10e287842d to your computer and use it in GitHub Desktop.
Physically more or less correct reflection of a ball on a round object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// physically more or less correct reflection of a ball on a round object (paddle) | |
// to simulate speed-loss at collision, multiply ballSpeed with a factor like 0.8f (line 21) | |
// if you wanted the paddle to bounce away, too, it would be in the reversed direction of refAngle | |
// but considering that both objects are moving now, you should also consider both | |
// objects' mass and current speed/dir of the paddle | |
// check for collisions | |
float minDist = mBall.getWidth()/2 + mPaddle.getWidth()/2; // radius ball + paddle | |
float dX = mBallX - mPaddleX; // horizontal difference between ball and paddle | |
float dY = mBallY - mPaddleY; // vertical diff... | |
float dist = (float) Math.sqrt(dX*dX + dY*dY); // distance between ball and paddle | |
// cross product of (dX,dY)x(mballspeedX,Y) < 0: they show in different directions | |
// means, the ball does not go away from the paddle but to it = there may be a new collision coming | |
float crossProd = dX*mBallSpeedX + dY*mBallSpeedY; | |
if(crossProd<0 && dist <= minDist) { // collision and ball moving to paddle | |
// atan2(Y,X) gives the angle of the cartesian coordinate | |
double refAngle = Math.atan2(dY, dX); // reflection angle (angle from paddle to ball) | |
double comingAngle = Math.atan2(-mBallSpeedY, -mBallSpeedX); // angle ball is coming, reversed direction | |
// angle ball shall go away, we take the difference between the reflectionAngle and the | |
// balls direction and a add it to the reflection angle | |
double goingAngle = refAngle + (refAngle-comingAngle); | |
// calculate new direction | |
float ballSpeed = (float) Math.sqrt(mBallSpeedX*mBallSpeedX + mBallSpeedY*mBallSpeedY); | |
mBallSpeedX = (float)(ballSpeed * Math.cos(goingAngle)); | |
mBallSpeedY = (float)(ballSpeed * Math.sin(goingAngle)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment