Ercan
Ercan

Reputation: 2773

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.

Upvotes: 3

Views: 4570

Answers (3)

Bill K
Bill K

Reputation: 62789

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.

Upvotes: 2

Tim Bender
Tim Bender

Reputation: 20442

Use Math#toRadians()

scale_X = Math.sin(Math.toRadians(angle));
scale_Y = Math.cos(Math.toRadians(angle));

Upvotes: 2

Eyal Schneider
Eyal Schneider

Reputation: 22446

Math.sin() and Math.cos() expect the angle in radians. You should transform your angles to radians (angle*Math.PI/180).

Upvotes: 7

Related Questions