Hello, I am roughly new to java only working with it for a couple months or so and have started my first major program. It is basically a Ragdoll avalanche type game where you dodge falling objects to win. My trouble is I cant seem to get the Collision working between the falling objects, which are JLabels btw, and the character, which I drew.
The character moves with the mouse and is drawn in its own class. I tried to use a rectangle method where I made a rectangle around the Objects falling and the characters head, which is a rectangle, but I just cant get it to work properly. I am hoping someone can help me figure out this collision problem with my application. I will be posting the classes which i use and hope someone can help me figure this out. Also any suggestions would be helpful.
Also I cant upload all the pictures used but I used 50x50 Png pictures for the falling objects and a png for the background. Once again thanks for any help or advice
public class PlayDodgeEm { Random number = new Random(); JFrame Gameframe = new JFrame("Dodge Em Game"); Icon ObjectPicture; //Creates the array of falling objects. Icon[] FallingObjects = new Icon[4]; //creates the array that holds how many objects will fall. JLabel[] CurrentObject = new JLabel[30]; JLabel Score = new JLabel(""); //decleration of multiple varialbes that will be used. int XPos, YPos; int ScoreCounter; int counter = 0; boolean collide, IsHead; public Rectangle Head; public Rectangle Object; int x1, y1, x2, y2; PlayDodgeEmPanel pane = new PlayDodgeEmPanel(); public PlayDodgeEm() { Gameframe.getContentPane().add(pane); //Sets the layout of the panel to null. pane.setLayout(null); //Adds the pictures to the array FallingObjects[0] = new ImageIcon(getClass().getResource("FlowerPot.png")); FallingObjects[1] = new ImageIcon(getClass().getResource("Anvil.png")); FallingObjects[2] = new ImageIcon(getClass().getResource("Computer.png")); FallingObjects[3] = new ImageIcon(getClass().getResource("ToolBox.png")); //Sets the default operation to close. Gameframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //Sets the size of teh screen. Gameframe.setSize(720, 640); //Sets resizable to false. Gameframe.setResizable(false); //Packs the screen to fit. Gameframe.pack(); //Sets the visibility to true. Gameframe.setVisible(true); //sets gameover to false. //Calls the method pick Picture PickPicture(); //Calls the method XPOsition XPosition(); pane.add(Score); //Creates a time with 70 miliseconds intervals and uses the actionListener MovingObjects Timer t = new Timer (10, MovingObjects); //starts the timer. t.start(); } public void AddPicture (){ //This method is used to add the picture to the pane with a randomly set X value. //Adds the picteur to the pane. //A try catch statement is used in case of an Index out of bounds exception in the array try{ pane.add(CurrentObject[counter]); }catch(ArrayIndexOutOfBoundsException exception){ } } //This action listener is called with every tick of the timer which is set to 10 milisecond intervals ActionListener MovingObjects = new ActionListener() { public void actionPerformed(ActionEvent evt) { //If the YPos is greater than 600... if(YPos > 600){ //Increment counter AddScore(); counter ++; //if counter equals 31 ... if (counter == 31){ //the frame visibility is set to false Gameframe.setVisible(false); //calls the GAmeoverFrame class; GameoverFrame GameOver = new GameoverFrame(); }else { //Ypos is reset to -20 YPos = -20; //CAlls method PIck Picture PickPicture(); //calls method XPosition XPosition(); } } //Calsl method AddPicture AddPicture(); //Calls method YPosition YPosition(); //calls method PictureMove. PictureMove(); PlayDodgeEmDraw SendCords = new PlayDodgeEmDraw(XPos, YPos); } }; public void PickPicture(){ //This method is used to randomly choose the image of the next falling object //A ramdom number is generated between 4 and 1 int PicNum = number.nextInt(3 - 0 + 1) + 0; //ObjectPicture stores the picture randomly chosen ObjectPicture = FallingObjects[PicNum]; //Adds the chosen picture into the array CurrentObject. //A try catch statement is used in case of an Index out of bounds exception in the array try{ CurrentObject[counter] = new JLabel (ObjectPicture); }catch(ArrayIndexOutOfBoundsException exception){ } } public void YPosition(){ //This method is used to continuelly change the YPos variable which is used to for the Y Position of the picture //Increments the YPos variable by 10. YPos = YPos + 20; } public void XPosition(){ //This method is used to randomly assigne the XPos variable with a value. //XPos is set to a random value between 700 and 1. XPos = number.nextInt(600 - 1 + 1) + 1; //Xpos is then added by 20 to create a space. XPos = XPos + 20; } public void PictureMove(){ //This method is used to move the picture on the screen with teh specified Xpos and YPos variables. //Sets the new bounds of the current picture. //A try catch statement is used in case of an Index out of bounds exception in the array try { CurrentObject[counter].setBounds(XPos, YPos, 50, 50); }catch (ArrayIndexOutOfBoundsException exception){ } } public void AddScore(){ //This method is used to add the users score each time an object goes off the screen. //Removes the previous score label to be replaced with the new updated one. pane.remove(Score); //The score counter is incremented. ScoreCounter ++; //tempScore takes the string value of the scoreCOunter to be used in a JLabel. String tempScore = String.valueOf(ScoreCounter); //Makes the JLAbel that will show the user their score. Score = new JLabel ("SCORE : " + ScoreCounter ); //Sets the font of the score label. Score.setFont(new Font("Comic Sans MS", Font.BOLD,20)); //Sets teh colore of teh score label. Score.setForeground(Color.blue); //Sets the bounds of the label to be in the upper right corner. Score.setBounds(600, 10, 200, 100); //Adds the score the the panel. pane.add(Score); //calls repaint method for the score. Score.repaint(); } }
The following is the class where I draw the charachter
Code: // Data : January, 2011 // imports java package import java.awt.*; // public clas PlayDodgeEmDraw public class PlayDodgeEmDraw { // declares variables public int x, y, PicX, PicY; Rectangle ObjRect; Rectangle Head; boolean collide = false; public final int WIDTH = 40, HEIGHT = 20; // open constructor public PlayDodgeEmDraw(){ } // constructor that takes in paramaters public PlayDodgeEmDraw(int PicXRec,int PicYRec){ // variable "PicX" = parameter PicX = PicXRec; // variable "PicY" = parameter PicY = PicYRec; // creates new rectangle with the x and y parameters ObjRect = new Rectangle(PicX, PicY, 50,50); } public void move(int xPos, int yPos) { // finds x position of mouse x = xPos; // finds y position of mouse y = yPos; } // draw method for the avatar ( stick man) public void draw(Graphics OBJ, int screenWidth) { // creates new variable named "baseX" which will equal the x coordinate from another method - variable "WIDTH" int baseX = x - WIDTH; // creates new variable named "baseY" which will equal the y coordinate from another method - variable "HEIGHT" / 2 int baseY = y - HEIGHT/2; // creates a new rectangle with the head coordinates Head = new Rectangle(baseX - 10, baseY, 75,50); //sends head (rectangle) to collision method Collision(Head); OBJ.setColor(Color.black); // draws head OBJ.fillRect(baseX - 10, baseY, 75,50); // color set to yellow OBJ.setColor(Color.yellow); // draws left eye OBJ.fillOval(baseX + 12, baseY + 10, 10 ,10); // draws right eye OBJ.fillOval(baseX + 32, baseY + 10, 10 ,10); // draws smile OBJ.fillArc(baseX + 13, baseY + 30, 25, 8, 170, 190); // color set to black OBJ.setColor(Color.black); // draws stick body OBJ.drawLine(baseX + 25, baseY + 50, baseX + 25, baseY + 70); // draws left leg OBJ.drawLine(baseX +24, baseY + 70, baseX + 10, baseY + 90); // draws right leg OBJ.drawLine(baseX +38, baseY + 90, baseX + 24, baseY + 70); // draws arms (with one line) OBJ.drawLine(baseX +10, baseY + 60, baseX + 40, baseY + 60); } // our collision method (which doesn't work properly) public void Collision(Rectangle Head) { collide = Head.intersects(ObjRect); if (Head.intersects(ObjRect)) { System.out.println("Collision : true"); } } }
And finally the panel for the game and also the MouseListeners to move the charachter
Code: // Data : January, 2011 // imports java packages import java.awt.*; import javax.swing.*; import java.awt.event.*; // public class "PlayDodgeEmPanel" extends the JPanel public class PlayDodgeEmPanel extends JPanel { // calls public PlayDodgeemDraw public PlayDodgeEmDraw PlayDodgeEmDraw; // private Image variables are declared. private Image image1; private Image currentImage; public PlayDodgeEmPanel() { // variable "Image1" will equal background picture image1 = (new ImageIcon("GameBackground1.png")).getImage(); // variable "currentimage" will equal "Image1" currentImage = image1; PlayDodgeEmDraw = new PlayDodgeEmDraw(); // declares new listener called "monitor" AvatarListener monitor = new AvatarListener(); // Mouse motion listner is added to our listener named "monitor" addMouseMotionListener(monitor); // Mouse listner is added to our listener named "monitor" addMouseListener(monitor); //Background color will be black if no picture is displayed setBackground (Color.black); // Preferred size of panel is 800 x 600 setPreferredSize(new Dimension(800, 600)); } // calls graphical paint component method public void paintComponent(Graphics page) { // uses super class super.paintComponent(page); // panel will draw the background image page.drawImage(currentImage, 0, 0, null); // sends information to the draw method of "PlayDodgeEmDraw" PlayDodgeEmDraw.draw(page, getWidth()); } // public class avatar listner will implement bouth the mouse motion and mouse listneners (monitor) public class AvatarListener implements MouseMotionListener, MouseListener { // public method for when the mouse is moved declared public void mouseMoved(MouseEvent event) { // calls and sends info to PlayDodgeEmDraw (x and y coords) PlayDodgeEmDraw.move(event.getX(), event.getY()); // repaints repaint(); } // public method for when the mouse is dragged public void mouseDragged(MouseEvent event) { // calls and sends info to PlayDodgeEmDraw (x and y coords) PlayDodgeEmDraw.move(event.getX(), event.getY()); // repaints repaint(); } // unused mouse method public void mousePressed(MouseEvent event) { } // unused mouse method public void mouseReleased(MouseEvent event) { } // unused mouse method public void mouseClicked(MouseEvent event) { } // unused mouse method public void mouseEntered(MouseEvent event) {} // unused mouse method public void mouseExited(MouseEvent event) {} } }