i’m writing a program that click JPanel and then a circle will spawn then its x & y will add 10 pixel per frame. The following two lines are temporarily to determine the next step after the circle spawn.
destinationX = -10 + (int)(Math.random() * ((10 - (-10)) + 1));
destinationY = -10 + (int)(Math.random() * ((10 - (-10)) + 1));
The above code is not the best to determine the position of the second steps of the cirlce. I want apply a method which make possibilities much more even. The following way is i about to do…..
x2,y2
/
/
/
/
/
h /
/
/ a
----------------------------
x1,y1
x1,y2 are known, a is random 360 degrees, h is 10, how to cal x2, y2?
Are you familiar with trigonometry? You have drawn a right triangle with
has the hypotenuse,aas the angle in question, an imaginary leg opposite (opp) of the angle, and a leg adjacent (adj) to the angle. Here’s an updated diagram:Trigonometry defines a function
sine (
sin) asopp / hand a similar functioncosine (
cos) asadj / h.In your case, you want to compute
x2 = x1 + adj.Since
cos(a) = adj / h,adj = h * cos(a); so by substitution we arrive atx2 = x1 + h * cos(a).We can do a similar derivation for
y2and gety2 = y1 + h * sin(a).If you want to move a point by a fixed amount in a random direction, you need
Math.sinandMath.cos: