Java: moving ball with angle?
I have started to learn game physics and I am trying to move a ball with an angle. But it does not change its angle. Java coordinate system is a little different and I think my problem is there. Here is my code.
This is for calculating x and y speed:
scale_X= Math.sin(angle);
scale_Y=Math.cos(angle);
velosity_X=(speed*scale_X);
velosity_Y=(speed*scale_Y);
This is for moving ball开发者_开发问答 in run() function:
ball.posX =ball.posX+(int)velosity_X;
ball.posY=ball.posY+(int)velosity_Y;
I used (int)velosity_X
and (int)velosity_Y
because in ball
class I draw object
g.drawOval(posX, posX, width, height);
and here g.drawOval
requires int
. I dont know if it is a problem or not. Also if I use angle 30 it goes +X and +Y but if I use angle 35 it goes -X and -Y. I did not figure out how to work coordinate system in Java.
Math.sin() and Math.cos() expect the angle in radians. You should transform your angles to radians (angle*Math.PI/180).
Use Math#toRadians()
scale_X = Math.sin(Math.toRadians(angle));
scale_Y = Math.cos(Math.toRadians(angle));
Check your types. You probably want everything to be floats because your scale variables are going to be less than one, greater than zero. If they are multiplied by ints, there is a good chance you will end up converting to a 1 or 0 all the time. I'm not completely sure of this, I'd code up a few simple equations to make sure (rather than memorize all the rules) if I were you.
One way to do it is to downcast your floats (or doubles) to int at the last possible moment (when you need to pass the values to a method call). This is a little bit of an overkill but doesn't hurt anything but CPU that you aren't using anyway--and may prevent bugs.
精彩评论