Im testing out collision detection for a game, The ball is traveling and i need to know when the ball hits a sloped line.
For this example i have used the whole screen, with a sloped line going from the top left corner to the bottom right corner.
I am working out the gradient using Y = MX + C
private int m;
private int c;
private float slopeY;
private void tryCollision(){
m = getHeight() / getWidth(); // change in Y / change in X
c = 0 // where the line crosses the x axis
slopeY = m * ball.x + c;
if(ball.y >= slopeY){
ball.ballStart = false; // ball will only move if it ballStart = true
}
}
Ball stopped moving where ever i place it on the screen. The problem is that working with gradients, Your meant to work with the y axis starting at the bottom going to the top, but in java the y axis starts at the top left corner going down. I have been told to invert the getHeight() number but i am unsure.
If you need to ask a question for you to help please leave a comment :)
Many Thanks, Charlton Santana
Found the answer :) ... when calculating M the equation would have turned out to 0.5265, as the variable being an int it would have automatically changed to 0 meaning the gradient would be a straight line so by changing the variable type it was able to work properly. I cant believe how simple the problem was. Thank for your help.! Hopefully people looking for collision detection for a gradient will be able to look at it as an example.!
slopeY = m *= ball.x + c;: Is there a reason for the*=in there? It seems to me that it should just be*. – Code-Guru Aug 21 '12 at 20:19m = getHeight() / getWidth();. You should not later change m with the*=assignment operator, as far as I can tell. I suggest using justy = m * ball.x + c;in the line under discussion. – Code-Guru Aug 21 '12 at 20:58