Sign in to follow this  

[java] Rectangle Collision

This topic is 3838 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In my "game" im trying to use rectangle collision detection, i got it to the point where 1 enemy can collide with 1 player but when i try to get that player to collide with a bunch of enemies in an array, the player only collides with the last enemy in the array. I have no idea why this is happening -This i have tried I tried creating new Rectangles for each enemy (an array of Rectangles) and then comparing those to the player, but i get the same result. -The original play was i just had a getRect() in the enemy class and i figured i could just call on the rect and compare them..for example if(player.getRec().intersects(enemy[i].getRec()) but that only works for the last in the array. If i manually create 2 enemies than it works perfect. Can anyone help me out? here ill post the relevant code, well what it was since i deleted it to retry many things. I am going to rewrite it and then post the whole code for you, but for now, i hope this helps. I didnt post the code originally because i figured you just couldnt check rectangle collision between many different things at once.. with the code below i have an array of enemy's and a player, p. *edit full code* i commented out the parts i thought were not relevant.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import javax.swing.*;

public class Game extends Applet implements Runnable, MouseMotionListener, KeyListener {
    private Image dbImage;
    private Graphics dbg;

    //RELEVANT*******

    Enemy[] enemy = new Enemy[5];
    /*
    Thread th;
    Player p = new Player(50,50,30,30);
    int x;
    int y,s;
    int speed = 10;
    int number;
    boolean left,right,up,down;
    
    
    public void init() {
        setSize(500,500);
        setBackground(Color.BLACK);
  */
        //RELEVANT
        for(int i = 0; i < enemy.length; i++) {
            int x = (int)Math.ceil(Math.random()*300);
            int y = (int)Math.ceil(Math.random()*300);
            enemy[i] = new Enemy(x,y,30,30,i);
            
        }
        /*
        
        addMouseMotionListener(this);
        addKeyListener(this);
        
    }
    
    public void start() {
        th = new Thread(this);
        th.start();
    }
    
    public void stop() {
        th.stop();
    }
    
    public void mouseDragged(MouseEvent e){
    }
    public void mouseMoved(MouseEvent e){
    }
    
    public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()) {
            case KeyEvent.VK_LEFT: left = true;break;
            case KeyEvent.VK_RIGHT: right = true;break;
            case KeyEvent.VK_UP: up = true;break;
            case KeyEvent.VK_DOWN: down = true;break;
            default:
        }
    }
    public void keyReleased(KeyEvent e) {
        switch(e.getKeyCode()) {
            case KeyEvent.VK_LEFT: left = false;break;
            case KeyEvent.VK_RIGHT: right = false;break;
            case KeyEvent.VK_UP: up = false;break;
            case KeyEvent.VK_DOWN: down = false;break;
            default:
        }
        
    }
    public void keyTyped(KeyEvent e) {
    }
    
    public void run() {
        
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        while (true) { 
*/

            //RELEVANT********

            for(int i = 0; i < enemy.length; i++) {
                if(enemy[i] != null) {
                    if(p.getRec().intersects(enemy[i].getRec())) {
                        number = 50;
                    } else {
                        number = 1;
                    }
                }
            }
            //Move player
            if(up) {
                p.moveY(-speed);
            }
            if(down) {
                p.moveY(speed);
                
            }
            
            if(left) {
                p.moveX(-speed);
            }
            if(right) {
                p.moveX(speed);
            }
            
            
            
            repaint();
            
            try {
                Thread.sleep(40);
            } catch (InterruptedException ex) {
                // do nothing
            }
            
            /*
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        }
    }
    
    public void paint(Graphics g) {
        Date d = new Date();
        g.setColor(Color.white);
        g.drawString(""+d,50,50);
        g.drawString(" "+number,100,300);
        
        //paint the enemy
        for(int i = 0; i < enemy.length; i++) {
            if(enemy[i] != null) {
                enemy[i].paint(g);
            }
        }
        
        p.paint(g);
    }
    
    
    public void update(Graphics g) {
        
        // initialize buffer
        if (dbImage == null) {
            dbImage = createImage(this.getSize().width, this.getSize().height);
            dbg = dbImage.getGraphics();
        }
        
        // clear screen in background
        dbg.setColor(getBackground());
        dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
        
        // draw elements in background
        dbg.setColor(getForeground());
        paint(dbg);
        
        // draw image on the screen
        g.drawImage(dbImage, 0, 0, this);
        
    }
    
}*/


and it only works for the last enemy.. here is my enemy code
import java.awt.*;

public class Enemy
{
    int x,y,w,h,i;
    public Enemy(int x_pos, int y_pos, int width, int height, int a)
    {
        x = x_pos;
        y = y_pos;
        w = width;
        h = height;
        i = a;
    }
    
    
    public int getX()
    {
        return x;
    }
    public int getY()
    {
        return y;
    }
    public int getWidth()
    {
        return w;
    }
    public int getHeight()
    {
        return h;
    }
    
    //RELEVANT**********

    public Rectangle getRec()
    {
        Rectangle r = new Rectangle(x,y,w,h);
        return r;
    }
    public void paint(Graphics g){
        g.setColor(Color.red);
        g.fillRect(x,y,w,h);
        g.setColor(Color.white);
        g.drawString(" "+i,x,y);
    }
}
Player code
import java.awt.*;

public class Player
{
    int x_pos,y_pos,w,h;
    int speed = 1;
    public Player(int x, int y, int width, int height)
    {
        x_pos = x;
        y_pos = y;
        w = width;
        h = height;
    }
    
    public void moveX(int speed)
    {   
        x_pos+=speed;
    }
    public void moveY(int speed)
    {
        y_pos+=speed;
    }
    
    public void switchSpeed()
    {
        speed = -speed;
    }
    
    public int getX()
    {
        return x_pos;
    }
    public int getY()
    {
        return y_pos;
    }
    public int getWidth()
    {
        return w;
    }
    public int getHeight()
    {
        return h;
    }
    
    //RELEVANT*********

    public Rectangle getRec()
    {
        Rectangle r = new Rectangle(x_pos,y_pos,w,h);
        return r;
    }
    
    public void paint(Graphics g)
    {
        g.setColor(new Color(250,250,250,50));
        g.fill3DRect(x_pos,y_pos,w,h,true);
    }
}

Share this post


Link to post
Share on other sites

// returns Enemy object that collided with the player
// or null if no such enemy
public Enemy CollisionTest( Player p, Enemy[] enemies)
{
Rectangle r = p.getRec();
for ( int i = 0; i < enemies.length; i++)
{
if(r.intersects(enemies[i].getRec()))
{
return enemies[i];
}
}
return null;
}


Share this post


Link to post
Share on other sites

This topic is 3838 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this