I’m new to Java programming, I am programming Java 1.6 with Android.
I have a simple function that makes a number go up and down between 0 and 200. I would like to put this into a Sine function but keep getting errors with what I’ve been trying.
I want my program to update an int (Number1) via a sine wave y axis.
Any ideas change the following logic into a Sine function? (disregard the 2nd number)
code:
private int Number1 = 150;
private int Number2 = 0;
private int counter = 0;
public void updateNumbers() {
if (counter == 0) {
if (Number1 < 200) {
Number1 = Number1 + 50;
Number2 = Number2 - 50;
if (Number1 >= 200) {
counter = 1;
}
}
} else if (counter == 1) {
if (Number2 < 200) {
Number1 = Number1 - 50;
Number2 = Number2 + 50;
if (Number2 >= 200) {
counter = 0;
}
}
}
}
Okay, so what you want to do is build a sine wave that goes between 0 and 200, but with what period? Did you want it to loop about every 8 calls?
How about this, leveraging the built-in Java
Math.sinfunction:Basically, we keep a variable that counts how many updates we’ve done, and scale that to match the period of a sine wave, 2*PI. That acts as the input to the ‘real’ sin function, giving us something that goes between -1 and 1 but has the right frequency. Then, to actually set the number, we just scale that to be between -100 and 100 and then add 100 to move it to be in the 0-200 range you wanted from the beginning.
(You don’t have to cast the number to an int if a double works for you, I was just keeping with the spirit of what you wrote above.)