Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Intersects method problems(FIXED)

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    29
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Intersects method problems(FIXED)

    I am trying to make a game in java were I have 3 objects, a bike, a rock and a coin. The objective of the game is to jump from different lanes using the arrows keys to avoid rocks while collecting coins. The problem is with the collision detection. I am using images for the objects and I'm trying to use the intersects method so I have also created rectangle objects with the same size and coordinates as the images and then check for their intersection. But whenever I check for the intersection it always returns false, and as a result the objects just go through eachother. I know that the program checks for the collision because I tried checking if their coordinates are the same and then it works. But ofcourse that is not nearly as precise as the intersects method and the result is pretty bad but works for testing. I have also tried to draw the rectangles following the images to see if they are following correctly and they are. I am not getting any errors and I have used the intersects method before and got it to work. Here is the code. The collision detection is in the class named Game and is checked for in the update method.
    	public void collision(){
     
    		for(Rock rock : rocks){
     
    		if(rock.rockRect.intersects(player.heroRect)){
    			System.out.println("Intersection");
    			going = false;
    			}
     
    	}
     
    		//Coin collision
    		if(coin.getY() + 60 == player.getY() && coin.getX() == player.getX() ){
    			System.out.println("coin");
    			score++;
    			try{
    				Thread.sleep(5);
    			}
    			catch(Exception e){}
    		}
     
    }

    The first if statement is with the intersects method(does not work) and the second is the one I used for testing(working). I have also tried switching them around so I know that it has nothing to do with the fact that im using an arraylist in the first if statement.

    Game class:
    import java.awt.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.ArrayList;
     
    import javax.swing.*;
     
     
    public class Game extends JFrame implements KeyListener, Runnable{
     
    	Player player;
     
    	Coin coin;
     
    	ArrayList<Rock> rocks;
     
    	int score;
     
    	Image dbi;
     
    	//Thread for objects other then the player
    	Thread objectThread;
     
    	Boolean loading = true;
     
    	Boolean going;
     
    	//Game constructor
    	public Game(){
    		player = new Player();
     
    		coin = new Coin();
     
    		rocks = new ArrayList<Rock>();
    		rocks.add(new Rock());
    		rocks.add(new Rock());
     
    		objectThread = new Thread(this);
     
    		score = 0;
     
    		setVisible(true);
    		setSize(225,400);
    		setResizable(false);
    		setLocation(550,250);
    		setDefaultCloseOperation(3);
    		setLayout(null);
     
    		addKeyListener(this);
     
    		going = true;
     
    		objectThread.start();
     
    		gameLoop();
     
    	}
     
    	//Method to draw everything
    	public void draw (Graphics g){
     
    		g.setColor(Color.gray);
    		g.fillRect(0, 0, 225, 400);
    		g.setColor(Color.YELLOW);
    		g.fillRect(65, 0, 10, 400);
    		g.fillRect(160, 0, 10, 400);
     
    		player.draw(g);
     
    		coin.draw(g);
     
    		for(Rock rock : rocks){
    		rock.draw(g);
    		}
     
    		g.setColor(Color.BLACK);
     
    		g.drawString("Score: " + score, 10, 50);
     
    	}
     
    	//Paint with double buffering
    	public void paint(Graphics g){
     
    		Image dbi = createImage(getWidth(),getHeight());
     
    		draw(dbi.getGraphics());
     
    		g.drawImage(dbi,0,0,null);
     
    		repaint();
     
    	}
     
    	//Check for collision
    	public void collision(){
     
    		for(Rock rock : rocks){
     
    		if(rock.rockRect.intersects(player.heroRect)){
    			System.out.println("Intersection");
    			going = false;
    			}
     
    	}
     
    		//Coin collision
    		if(coin.getY() + 60 == player.getY() && coin.getX() == player.getX() ){
    			System.out.println("coin");
    			score++;
    			try{
    				Thread.sleep(5);
    			}
    			catch(Exception e){}
    		}
     
    }
     
    	//Update the movement
    	public void update(){
    		//If right has been pressed
    		if(player.checkDirection() == 1){
     
    			if(player.getX() == 0){
    				player.setX(78);
     
    				try{
    					Thread.sleep(150);
    				}catch(Exception e){}
    			}
    			else if(player.getX() == 78){
    				player.setX(155);
     
    				try{
    					Thread.sleep(150);
    				}catch(Exception e){}
    			}
    			else{}
     
    		}
     
    		//If left has been pressed
    		if(player.checkDirection() == 2){
    			if(player.getX() == 155){
    				player.setX(78);
     
    				try{
    					Thread.sleep(150);
    				}catch(Exception e){}
    			}
    			else if(player.getX() == 78){
    				player.setX(0);
     
    				try{
    					Thread.sleep(150);
    				}catch(Exception e){}
    			}
     
    		}
    		collision();
     
    	}
     
    	//Update for objects other then the player
    	public void objectUpdate(){
    		for(Rock rock : rocks){
    		rock.yMovement();
    		}
    		coin.yMovement();
    		try{
    			Thread.sleep(4);
    		}catch(Exception e){}
     
    	}
     
    	//Keeps the game going
    	public void gameLoop(){
    		while(going){
     
    			update();
     
    		}
     
    		JOptionPane.showMessageDialog(this,"GAME OVER");
    	}
     
    	//Loop for objects other then the player
    	public void objectLoop(){
    		while(going){
    			objectUpdate();
    		}
    	}
     
    	//Checking for keyboardEvents
    	public void keyPressed(KeyEvent e) {
    		int keyCode = e.getKeyCode();
     
    		if(keyCode == KeyEvent.VK_RIGHT){
    			player.setRight(true);
    		}
    		if(keyCode == KeyEvent.VK_LEFT){
    			player.setLeft(true);
    		}
     
    	}
    	//Checking for keyboardEvents
    	public void keyReleased(KeyEvent e) {
     
    		int keyCode = e.getKeyCode();
     
    		if(keyCode == KeyEvent.VK_RIGHT){
    			player.setRight(false);
    		}
    		if(keyCode == KeyEvent.VK_LEFT){
    			player.setLeft(false);
    		}
    	}
     
    	//Checking for keyboardEvents
    	public void keyTyped(KeyEvent arg0) {}
     
     
    	public void run() {
    		objectLoop();
    	}
     
    }//End class Game

    Player/Bike class:
    import java.awt.*;
    import javax.swing.ImageIcon;
     
    public class Player {
     
    	Image hero;
    	Rectangle heroRect;
     
    	int heroX;
     
    	int heroY;
     
    	Boolean moveLeft,moveRight;
     
    	//Player constructor
    	public Player(){
     
    		loadImages();
    		setX(0);
    		setY(275);
    		heroRect = new Rectangle(heroX,heroY,75,90);
     
    		moveLeft = false;
    		moveRight = false;
     
    	}
     
    	//Draw the player
    	public void draw(Graphics g){
    		g.drawImage(hero,heroX,heroY,null);
    		g.setColor(Color.blue);
    		g.drawRect(heroX, heroY, 75, 90);
     
    	}
     
    	//Load the player images
    	public void loadImages(){
    		hero = new ImageIcon("C:/Users/Albin/Desktop/SpriteBike.png").getImage();
    	}
     
    	//Set the direction
    	public void setRight(Boolean b){
    		moveRight = b;
    	}
     
    	//Set the direction
    	public void setLeft(Boolean b){
    		moveLeft = b;
    	}
     
    	//Get x position
    	public int getX(){
    		return heroX;
    	}
     
    	//Get y position
    	public int getY(){
    		return heroY;
    	}
     
    	//Set x position
    	public void setX(int x){
    		heroX = x;
    	}
     
    	//Set y position
    	public void setY(int y){
    		heroY = y;
    	}
     
    	//Check which direction is pressed
    	public int checkDirection(){
     
    		if(moveRight == true)
    			return 1;
     
    		else if(moveLeft == true)
    			return 2;
     
    		else
    			return 0;
    	}
    }//End class Player

    Rock class:
    import java.awt.*;
    import java.util.Random;
    import javax.swing.ImageIcon;
     
    public class Rock {
     
    	Image rock;
    	Player p;
     
    	Rectangle rockRect;
     
    	int rockX,rockY;
     
    	//Rock constructor
    	public Rock(){
     
    		loadImages();
     
    		randomXPosition();
     
    		setY(-25);
     
    		p = new Player();
    		rockRect = new Rectangle(rockX,rockY,70,65);
     
    	}
     
    	//Draw the rock
    	public void draw(Graphics g){
    		g.drawImage(rock,rockX,rockY,null);
    		g.setColor(Color.red);
    		g.drawRect(rockX, rockY, 70, 65);
     
    	}
     
    	//Load the rock images
    	public void loadImages(){
    		rock = new ImageIcon("C:/Users/Albin/Desktop/SpriteStone.png").getImage();
    	}
     
    	//Set a random x position
    	public void randomXPosition(){
    		Random r = new Random();
     
    		int x = r.nextInt(3);
     
    		if(x == 0){
    			setX(0);
    		}
    		else if(x == 1){
    			setX(78);
    		}
    		else if(x == 2){
    			setX(155);
    		}
     
    	}
     
    	//Get x position
    		public int getX(){
    			return rockX;
    		}
     
    	//Get y position
    		public int getY(){
    			return rockY;
    		}
     
    	//Set x position
    		public void setX(int x){
    			rockX = x;
    		}
     
    	//Set y position
    		public void setY(int y){
    			rockY = y;
    		}
     
    	//Move the y coordinate
    	public void yMovement(){
    		rockY += 1;
     
    		if(getY() >= 410){
    			setY(-25);
    			randomXPosition();		
    		}
    	}
     
    }//End class Rock

    Coin class:
    import java.awt.*;
    import java.util.Random;
    import javax.swing.ImageIcon;
     
    public class Coin {
     
    	Image coin;
    	Rectangle coinRect;
     
    	int coinX;
    	int coinY;
     
    	public Coin(){
     
    		randomXPosition();
    		coinY = -75;
     
    		loadImages();
    		coinRect = new Rectangle(coinX,coinY,65,45);
     
    	}
     
    	public void loadImages(){
    		coin = new ImageIcon("C:/Users/Albin/Desktop/SpriteCoin.png").getImage();
    	}
     
    	public void draw(Graphics g){
    		g.drawImage(coin,coinX,coinY,null);
    	}
     
    	public void randomXPosition(){
    		Random r = new Random();
     
    		int x = r.nextInt(3);
     
    		if(x == 0){
    			setX(0);
    		}
    		else if(x == 1){
    			setX(78);
    		}
    		else if(x == 2){
    			setX(155);
    		}
     
    	}
     
    	public void yMovement(){
    		coinY += 1;
     
    		if(getY() >= 410){
    			setY(-25);
    			randomXPosition();		
    		}
    	}
     
    	public void setX(int x){
    		coinX = x;
    	}
     
    	public void setY(int y){
    		coinY = y;
    	}
     
    	public int getX(){
    		return coinX;
    	}
     
    	public int getY(){
    		return coinY;
    	}
     
    }

    I'm really tired of this problem and I would be really happy if someone knew what the problem was. If you want me to point out more specific information from the code so you don't have to look through it all just tell me. But it might take awhile for me to answer since I might be busy but I will do my best. Happy for your time.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Intersects method problems

    first if statement is with the intersects method(does not work)
    Have you tried debugging the code by using println statements? For example add a println() statement just before this statement:
    if(rock.rockRect.intersects(player.heroRect)){
    that prints out the values of rockRect and heroRect. The printout will show you where the rectangles are and if they intersect.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    albin1228 (August 22nd, 2013)

  4. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    29
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Intersects method problems

    Quote Originally Posted by Norm View Post
    Have you tried debugging the code by using println statements? For example add a println() statement just before this statement:
    if(rock.rockRect.intersects(player.heroRect)){
    that prints out the values of rockRect and heroRect. The printout will show you where the rectangles are and if they intersect.
    Well I did print out some other things earlier but I didn't know you could print the entire rectangle! I did that and I saw that for some reason the rectangles weren't updating their x and y . For some reason their x and y were not updating when the images x and y were and they were using the same variables for coordinates. Anyways the way i fixed it was I added so it directly sets the coordinates for the rectangles whenever it changes for the picture:
    public void setX(int x){
    			rockX = x;
    			rockRect.x = x;
    		}

    I added the rockRect.x = x in every method which has the job to set the coordinates. Thank you very much for helping me solve my problem! This has bothered me for a while!

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Intersects method problems(FIXED)

    Why have the location of the rock in two places: the rectangle and the rockX variable?
    Having the Rock's location saved in just one place would be less confusing.
    Get rid of the rockX and rockY variables.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. intersects method
    By game06 in forum Java Theory & Questions
    Replies: 6
    Last Post: March 31st, 2013, 01:06 AM
  2. problems with my toString method
    By tyneframe in forum Object Oriented Programming
    Replies: 1
    Last Post: February 2nd, 2013, 12:50 PM
  3. Problems With Method Calls and Variables
    By connor3452 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 17th, 2012, 05:46 AM
  4. problems with equals method.
    By mkarthik90 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 29th, 2012, 11:11 PM
  5. Acessor Method Problems for Projectile Motion
    By Kaiki in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 28th, 2011, 08:01 PM

Tags for this Thread