Drawing Lab 4 - Animation
Create a new Java Class called AnimationBasics. Add the code below to make a standard JPanel drawing example.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class AnimationBasics extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
AnimationBasics game = new AnimationBasics();
frame.add(game);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Next add the code below to create an animated ball.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class AnimationBasics extends JPanel {
int x = 0; // X position of ball
int y = 0; // Y position of ball
int xa = 1; // X direction/acceleration of ball
int ya = 1; // Y direction/acceleration of ball
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Draw Ball at X and Y
g2d.fillOval(x, y, 30, 30);
}
public void moveBall() {
//Move Ball based on xa and ya
x += xa;
y += ya;
// Check to see if ball is on edge of screen
// and change xa or ya accordingly
if (x > 400 - 45)
xa = -1;
if (y > 400 - 65)
ya = -1;
if (x < 0)
xa = 1;
if (y < 0)
ya = 1;
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
AnimationBasics game = new AnimationBasics();
frame.add(game);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Main Game Loop
while (true) {
// Call the moveBall method
game.moveBall();
// Repaint the screen
game.repaint();
// Wait 10ms
Thread.sleep(10);
}
}
}
To Do |
|
Your assignment is to create a Red Ball and a Blue Ball in this project.
Each ball will need it's own variables (x,y,xa,ya) [variables will need to be named different EX: blueX, blueY, blueXA, blueYA] and its own moveBall method.
Blue Ball should start at (100,100) with xa = 1 and ya = -1
Red Ball should start at (300,300) with xa = -1 and ya = -1
Each ball will need it's own variables (x,y,xa,ya) [variables will need to be named different EX: blueX, blueY, blueXA, blueYA] and its own moveBall method.
Blue Ball should start at (100,100) with xa = 1 and ya = -1
Red Ball should start at (300,300) with xa = -1 and ya = -1