Okay, I’m trying to create a method to handle collisions between a rect and a circle. this is how far I’ve gotten, but now I’m stumped. It only works properly if px and py < the circles center.
Here’s the method
public boolean col(){
float planeAngle = (float) Math.toDegrees(Math.atan2(px - (px + pwidth), -(py - py)));
float planeWidth = rotate(px + pwidth,py + pheight, px,py,planeAngle,true);
float planeHeight = rotate(px + pwidth,py + pheight, px,py,planeAngle,false);
float planeCentX = (planeWidth/2);
float planeCentY = (planeHeight/2);
float dist = (float) Math.sqrt(Math.pow((bx + (bsize/2)) - planeCentX, 2) + Math.pow(-((by + (bsize/2)) - planeCentY), 2));
if(dist <= (bx + (bsize/2)))
return true;
else
return false;
}
and here is the full source: (requires slick)
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
public class ColTest extends BasicGame{
float px = 50;
float py = 50;
float pheight = 50;
float pwidth = 50;
float bx = 200;
float by = 200;
float bsize = 200;
float pspeed = 3;
Input input;
public ColTest()
{
super("ColTest");
}
@Override
public void init(GameContainer gc)
throws SlickException {
}
@Override
public void update(GameContainer gc, int delta)
throws SlickException
{
input = gc.getInput();
try{
if(input.isKeyDown(Input.KEY_UP))
py-=pspeed;
if(input.isKeyDown(Input.KEY_DOWN))
py+=pspeed;
if(input.isKeyDown(Input.KEY_LEFT))
px-=pspeed;
if(input.isKeyDown(Input.KEY_RIGHT))
px+=pspeed;
}
catch(Exception e){}
}
public void render(GameContainer gc, Graphics g)
throws SlickException
{
g.drawString("col: " + col(), 10, 10);
g.fillRect(px, py, 50, 50);
g.fillOval(200, 200, 200, 200);
}
public boolean col(){
float planeAngle = (float) Math.toDegrees(Math.atan2(px - (px + pwidth), -(py - py)));
float planeWidth = rotate(px + pwidth,py + pheight, px,py,planeAngle,true);
float planeHeight = rotate(px + pwidth,py + pheight, px,py,planeAngle,false);
float planeCentX = (planeWidth/2);
float planeCentY = (planeHeight/2);
float dist = (float) Math.sqrt(Math.pow((bx + (bsize/2)) - planeCentX, 2) + Math.pow(-((by + (bsize/2)) - planeCentY), 2));
if(dist <= (bx + (bsize/2)))
return true;
else
return false;
}
public float rotate(float x, float y, float ox, float oy, float a, boolean b)
{
float dst = (float) Math.sqrt(Math.pow(x-ox,2.0)+ Math.pow(y-oy,2.0));
float oa = (float) Math.atan2(y-oy,x-ox);
if(b)
return (float) Math.cos(oa + Math.toRadians(a))*dst+ox;
else
return (float) Math.sin(oa + Math.toRadians(a))*dst+oy;
}
public static void main(String[] args)
throws SlickException
{
AppGameContainer app =
new AppGameContainer( new ColTest() );
app.setShowFPS(false);
app.setAlwaysRender(true);
app.setTargetFrameRate(60);
app.setDisplayMode(800, 600, false);
app.start();
}
}