I am trying to determine collision in a 2D Side Scroller environment using Rectangles. However, the way most people do it is to get the bounds of the Tile. I do not use Tile's in this case, I am just drawing Simple Full Colored Rectangles using Graphics2D.
g.drawRect(int x, int y, int width, int height)
I would obviously need a GameObject Class, which I have below, and I do check for an intersect, but I don't think that would actually check for collision because I dont know where it should be called. Also, how would you know which parameters to pass? I also do not believe that I need everything in the class, and maybe I am missing something. It would be greatly appreciated if someone could give me tips to improve upon the class aswell.
package com.github.geodox.echo.game.entity;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import com.github.geodox.echo.game.GamePanel;
public abstract class GameObject
{
//SpriteImage
protected BufferedImage objImage;
protected double xmap;
protected double ymap;
//Position and Vector
protected double x;
protected double y;
protected double mx;
protected double my;
//Dimensions
protected int width;
protected int height;
//Animation
protected Animation animation;
protected int currentAction;
protected int previousAction;
//Direction
protected boolean forward;
protected boolean jumping;
protected boolean falling;
//Movement
protected double moveSpeed;
protected double maxSpeed;
protected double stopSpeed;
protected double fallSpeed;
protected double maxFallSpeed;
protected double jumpStart;
protected double stopJumpSpeed;
public GameObject()
{
}
public boolean intersects(GameObject o)
{
Rectangle r1 = getRectangle();
Rectangle r2 = o.getRectangle();
return r1.intersects(r2);
}
public Rectangle getRectangle()
{
return new Rectangle((int)x - width, (int)y - height, width, height);
}
public int getX()
{
return (int) x;
}
public int getY()
{
return (int) y;
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public void setPosition(double x, double y)
{
this.x = x;
this.y = y;
}
public void setVector(double mx, double my)
{
this.mx = mx;
this.my = my;
}
public void setDirection(boolean forward)
{
this.forward = forward;
}
public void setJumping(boolean jumping)
{
this.jumping = jumping;
}
public void setFalling(boolean falling)
{
this.falling = falling;
}
public boolean notOnScreen()
{
return x + width < 0 || x - width > GamePanel.getWindowWidth() || y + height < 0 || y - height > GamePanel.getWindowHeight();
}
}