Forest Hills High School



2D Graphics TutorialThe goal of this assignment is to teach you how to make 2D graphics with java. You will have 6 tasks. Task 1: Basic setupCreate a class called LearningGraphics.java.Copy and paste the following import statements into LearningGraphics.javaimport java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import javax.swing.JComponent;import javax.swing.JFrame;import java.awt.Font;Copy and paste the following YELLOW code below the import statements in LearningGraphics.javapublic class LearningGraphics extends JComponent implements KeyListener, MouseListener{ //instance variables private int WIDTH; private int HEIGHT; //Default Constructor public LearningGraphics() { //initializing instance variables WIDTH = 1000; HEIGHT = 500; //Setting up the GUI } //This method will acknowledge user input public void keyPressed(KeyEvent e) { //getting the key pressed //moving the rectangle } //All your UI drawing goes in here public void paintComponent(Graphics g) { //Drawing a Blue Rectangle to be the background //Drawing Hello World!! at the center of the GUI //Drawing the user-controlled rectangle //Drawing the autonomous circle } public void loop() { //making the autonomous circle move //handling when the circle collides with the edges //handling the collision of the circle with the rectangle //Do not write below this repaint(); } //These methods are required by the compiler. //You might write code in these methods depending on your goal. public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void start(final int ticks){ Thread gameThread = new Thread(){ public void run(){ while(true){ loop(); try{ Thread.sleep(1000 / ticks); }catch(Exception e){ e.printStackTrace(); } } } }; gameThread.start(); } public static void main(String[] args) { LearningGraphics g = new LearningGraphics(); g.start(60); }}Type or copy and paste the following in the default constructor under //Setting up the GUI. (Typing it yourself will help you learn/understand it better) JFrame gui = new JFrame(); //This makes the gui box gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Makes sure program can close gui.setTitle("Learning Graphics"); //This is the title of the game, you can change it gui.setPreferredSize(new Dimension(WIDTH + 5, HEIGHT + 30)); //Setting the size for gui gui.setResizable(false); //Makes it so the gui cant be resized gui.getContentPane().add(this); //Adding this class to the gui /*If after you finish everything, you can declare your buttons or other things *at this spot. AFTER gui.getContentPane().add(this) and BEFORE gui.pack(); */ gui.pack(); //Packs everything together gui.setLocationRelativeTo(null); //Makes so the gui opens in the center of screen gui.setVisible(true); //Makes the gui visible gui.addKeyListener(this); gui.addMouseListener(this); gui.addMouseMotionListener(this);Run your program (Note the main is declared as the final method). You should see a grey window pop up. Close the window.In the constructor under //initializing instance variables you should see that the WIDTH and the HEIGHT have been initialized to 1000 and 500. Change these numbers and run your program again. You should see the size change. Set the dimensions back to 1000x500 for the remainder of this tutorial.NOTE: (0,0) IS THE TOP LEFT.The X increases to the right and 2963337302500The Y increases downward!Assuming that WIDTH = 1000 and HEIGHT = 500, the diagram would be Task 2: Setting up the backgroundFind the paintCompontent() method. Notice the parameter is a Graphics named g.118624941103400The way that drawing works in java is that you first set your color and then you draw the shape you want. So, drawing always takes 2 lines of code. (If you do not change your color then you will still draw your shapes, but you won’t be able to see the second shape since it will be hidden in the first shape.)Here is the setColor() method of the Graphics class. This allows you to choose your color.-12700015324600Under //Drawing a Blue Rectangle to be the background, set the color to blue.Here is the fillRect() method of the Graphics class. The following method draws a rectangle on the screen.Create a rectangle at (0,0) with a width of WIDTH and a height of HEIGHT.Run your program and make sure that the appropriate result is displayed. If not, then go back and check your work.-1482-13864200Task 3: Writing text on the GUIHere is a parameterized constructor for the Font class.In the paintComponent() method under //Drawing Hello World!! at the center of the the GUI, declare and instantiate a Font object using the constructor above. The font name should be Arial, the style should be bold, and the size should be 50.Here is the method header of the mutator method from the Graphics class that sets the font for the current graphics.public void setFont(Font f)Set the font of g to the font you created earlier.center698500Call the setColor() method and set the color to black.Here is the drawString() method of the Graphics class. The following method draws a String on the screen.Call the drawString() method on g to draw “Hello World!!” at the center of the GUI. You should use WIDTH and HEIGHT in this call.Run your program and make sure that the appropriate result is displayed. If not, then go back and check your work.Task 4: Making a user-controlled rectangleFor a user-controlled rectangle, we will need 4 int instance variables. 2 ints to represent the location (x, y) of the rectangle and 2 more ints to represent the width and height of the rectangle.Declare 4 int instance variables named rX, rY, rW, and rH. (rX, rY) represent the location of the rectangle and rW and rH represent the width and height of the rectangle.In the default constructor under //initializing instance variables, initialize the rectangle to start at position (300,300) with a width of 50 and a height of 100. Now go to the paintComponent() method and under //Drawing the user-controlled rectangle set the color of g to red.Draw a rectangle at (rX, rY) with the dimensions rW x rH.Run your program and make sure that the appropriate result is displayed. If not, then go back and check your work.Find the keyPressed() method. Notice the parameter is a KeyEvent object named e.Here is the getKeyCode() method of the KeyEvent class. The following method returns an int that represents the key that was pressed. Each key on the keyboard has a number associated with it. public void getKeyCode()In keyPressed() under //getting the key pressed, call the getKeyCode() method on e and store the result in an int named key. Print the result returned.Run your program. Press some keys on your keyboard. You should see some numbers displaying on the output prompt. These numbers represent the values of each key. When you write your game you could decide which keys to use. For example you could choose the arrow keys or wasd. Let’s use the ARROW KEYS for the sake of this tutorial. The value for up is 38, down is 40, left is 37, and right is 39.In the keyPressed() method we will move the rectangle using if-statements. This will require 1 chain of length 4. You will need to use the values you chose from the previous step.Under //moving the rectangle write the if-statement chain. Each condition will check if key represents a desired number. Let’s first code for up. Check to see if key equals 38, if so then minus 10 from rY. (Recall Y gets smaller as you go UP)Run your program, press the up-arrow key. Confirm that the rectangle moves up.Apply the same logic and continue with this chain to handle the other 3 directions.Run your program, confirm that the rectangle moves in all 4 directions.Task 5: Making a circle that moves on its own. (Autonomous Circle)For the autonomous circle, we will need 5 int instance variables. 2 ints to represent the location (x, y) of the circle, another int to represent the diameter of the circle, and 2 more to represent the velocity (SPEED) of the circle in each direction.Declare 5 int instance variables named cX, cY, diam, cVx and cVy. (cX, cY) represent the location of the circle, diam represents the diameter of the circle and cVx and cVy represent the velocity of the circle in the respective directions.In the default constructor under //initializing instance variables, initialize the circle to start at position (500,300) with a diameter of 70 and set both velocities to 5.-27093310244700Now go to the paintComponent() method and under //Drawing the autonomous circle set the color of g to yellow.Here is the fillOval() method of the Graphics class. The following method draws an Oval on the screen.Call the fillOval() method and set the location to cX,cY, and set the width and height to diam.388408486800Run your code. You should now see a yellow circle on the screen. Here are some facts you should acknowledge. You will need ALL these facts very soon.Let’s make the circle move to the RIGHT on its own. Find the loop() method. Under //making the autonomous circle move, add cVx to cX, by writing cX+=cVx;Run the program and make sure that the circle moves to the right on its own.Now let’s make the circle move diagonally to the bottom right. Under the previous line add cVy to cY by writing cY+=cVy;Run your program, confirm that the circle moves down-right. Notice the circle leaves the screen. We need to fix this in the next few steps.Let’s handle the circle hitting the bottom edge first. In loop() and under //handling when the circle collides with the edges, declare 2 ints named nextX and nextY that will represent the future x coordinate of the circle, and the future y coordinate of the circle.Assign nextX the sum of cX and cVx. Assign nextY the sum of cY and cVy. Now we will check if the NEXT position of the circle is out of the grid. If so, then we will change the direction of the circle depending on which direction it should go. For example, if the circle is going DOWN and hits the bottom edge of the screen then it should start moving UP.You will now need to write a chain of if-statements. As you write these if-statements you need to recall the image of the yellow circle above. Let’s handle the circle hitting the bottom boarder first. The bottom boarder is the HEIGTH of the screen.To handle the bottom of the circle you only have to worry about the NEXT Y value. But because the nextY value represents the TOP-LEFT of the circle you also need to add the diameter of the circle. Therefore, you need to check if nextY + diam is greater than the HEIGHT. If this is true, then multiply the direction in the Y direction by -1. Run your program, you should now see the circle hit the bottom boarder and start moving in the top-left direction and leaving the screen.Apply the same logic from step (p) and continue the if-statement chain so it bounces off the other 3 boarders. Run your program as you add to the chain, confirm that your code works.Task 6: Making a circle collide with the red rectangle.Now for the difficult part. Finally let’s make the yellow-circle bounce off the red user-controlled paddle.We will need 2 helper methods for this. First write a method called distance() that will accept the 4 ints x1, y1, x2, y2 and return a double. This method should perform the distance formula.center571500Next write another method called detectCollision(), this method will return a boolean and have no parameters. The purpose of this method is to detect when the circle collides with the red rectangle. When it does it should return true, otherwise it should return false.Here is a short explanation of how this method is going to work. We check the distance from each pixel of the rectangle to the center of the circle. If this distance is less than the radius of the circle then that means that the rectangle and the circle have collided.In detectCollision() declare a boolean output and initialize it to false.To write this method we will need to calculate store 3 values. The radius of the circle, which is just the diam/2, and the x and y coordinate of the CENTER of the circle. Declare the 3 ints radius, centerX, and centerY. Assign the appropriate value to radius.Declare and assign 2 more ints named nextX and nextY. Same exact code that you wrote in steps (5l, 5m).Recall that to find the center (or middle) of 2 numbers all you have to do is find the average of those numbers. That is why centerX = (2*nextX + diam)/2 and centerY = (2*nextY + diam)/2. (I used the diagram of the yellow circle above to figure out these values.)1074843-11853300Here is an image that shows all 4 vertices of the red rectangle. You will need this for the next step.You are about a set of nested for-loops. The outer loop iterates through each pixel in the X direction, meaning it will go from rX to rX + rW inclusive. The inner loop will iterate through each pixel in the Y direction, meaning it will go from rY to rY + rH inclusive.In the nested loop check to see if the distance from the current pixel (the 2 ints that you declared in your for loops) to the CENTER of the circle is less than the radius. If it is then set output to true. DO NOT write an else here. AFTER the loops return output.Finally, in the loop() method find the comment //handling the collision of the circle with the rectangle. Under this call the method detectCollision(). If it returns true change the direction of BOTH cVx and cVy by multiplying each of them by -1. Disclaimer, depending on what game you want to make you should modify this detectCollision() method to satisfy your needs.Useful methods of the Graphics classpublic void setColor(Color c)public void setFont(Font f)public void drawString(String msg, int x, int y)public void fillRect(int x, int y, int width, int height)public void drawRect(int x, int y, int width, int height)public void fillOval(int x, int y, int width, int height)public void drawOval(int x, int y, int width, int height)public void drawLine(int x1, int y1, int x2, int y2) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download