Reputation: 830
I am trying to make an ImageView
change its position based on the direction it is facing.
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class Demo extends Application {
public void start(Stage window) {
window.setTitle("Changing ImageView position based on angle of rotation");
int speed = 10; // You can modify the speed here
ImageView imageView = new ImageView(new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTBJoRKh1UKimWTSLdabW2b8RSLDeSgMfSqqg&usqp=CAU"));
imageView.setX(100);
imageView.setY(100);
imageView.setRotate(65); // This is where you can change the angle of rotation
Group root = new Group();
root.getChildren().add(imageView);
Scene scene = new Scene(root);
window.setScene(scene);
final long[] lastNanoTime = {System.nanoTime()};
new AnimationTimer() {
@Override
public void handle(long currentTime) {
double elapsedTime = (currentTime - lastNanoTime[0]) / 1000000000.0;
lastNanoTime[0] = currentTime;
imageView.setX(imageView.getX() + Math.sin(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
imageView.setY(imageView.getY() + Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
}
}.start();
window.show();
}
public static void main(String[] args) {
launch(args);
}
}
The above code is based on the code I am using. You can adjust the degrees accordingly to see the issue. The ImageView
does not move in the direction it is facing. Note: I found a random .png file online for the purpose of this demo. You can substitute with a different image in you own code in order to better visualize the problem.
The issue is, the ImageView
does not move in the direction it is facing. When oriented vertically (0° or 180°) the ImageView
moves backward, but when oriented horizontally (90° or 270°) it moves straight ahead like it should. When oriented diagonally, it moves somewhere in between.
What am I doing wrong and how do I fix it?
Upvotes: 1
Views: 288
Reputation: 18792
The direction of the y
axis is down. So when the angle is 0 and you increase y
value you'll get down movement.
To make the image move up when the angle is 0 simplט change the increment sign from:
imageView.setY(imageView.getY() + Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
to
imageView.setY(imageView.getY() - Math.cos(Math.toRadians(imageView.getRotate())) * speed * elapsedTime);
Upvotes: 1