In: Computer Science
using java program Stay on the Screen! Animation in video games is just like animation in movies – it’s drawn image by image (called “frames”). Before the game can draw a frame, it needs to update the position of the objects based on their velocities (among other things). To do that is relatively simple: add the velocity to the position of the object each frame.
For this program, imagine we want to track an object and detect if it goes off the left or right side of the screen (that is, it’s X position is less than 0 and greater than the width of the screen, say, 100). Write a program that asks the user for the starting X and Y position of the object as well as the starting X and Y velocity, then prints out its position each frame until the object moves off of the screen. Design (pseudocode) and implement (source code) for this program.
Sample run 1:
Enter the starting X position: 50
Enter the starting Y position: 50
Enter the starting X velocity: 4.7
Enter the starting Y velocity: 2
X:50 Y:50
X:54.7 Y:52
X:59.4 Y:54
X:64.1 Y:56
X:68.8 Y:58
X:73.5 Y:60
X:78.2 Y:62
X:82.9 Y:64
X:87.6 Y:66
X:92.3 Y:68
X:97 Y:70
X:101.7 Y:72
Sample run 2:
Enter the starting X position: 20
Enter the starting Y position: 45
Enter the starting X velocity: -3.7
Enter the starting Y velocity: 11.2
X:20 Y:45
X:16.3 Y:56.2
X:12.6 Y:67.4
X:8.9 Y:78.6
X:5.2 Y:89.8
X:1.5 Y:101
X:-2.2 Y:112.2
If you have any doubts, please give me comment...
import java.util.Scanner;
public class FrameAnimation{
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double X, Y, X_Velocity, Y_Velocity;
System.out.print("Enter the starting X position: ");
X = scnr.nextDouble();
System.out.print("Enter the starting Y position: ");
Y = scnr.nextDouble();
System.out.print("Enter the starting X velocity: ");
X_Velocity = scnr.nextDouble();
System.out.print("Enter the starting Y velocity: ");
Y_Velocity = scnr.nextDouble();
System.out.println("X:"+X+"\t"+"Y:"+Y);
while(X>=0 && X<=100){
X += X_Velocity;
Y += Y_Velocity;
System.out.printf("X:%.1f\tY:%.1f\n", X, Y);
}
}
}