Possible Duplicate:
Java rectangle collision detection confusion
I have run into a problem with collision detection, I have asked around other forums and been searching Google for a month now (No one had an answer). My problem with collision detection is that it’s delayed or inaccurate, sometimes it detects it perfectly, sometimes halfway through and sometimes not at all. Some people say it’s a synchronicity problem between my update loop (using swing timer) and KeyInput. What do you think?
Code! 🙂
KeyInput:
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_D && walkRight == true)
{
Screen.movementX=-1;
}
else if (key == KeyEvent.VK_A && walkLeft == true)
{
Screen.movementX=1;
}
else if (key == KeyEvent.VK_S && walkDown == true)
{
Screen.movementY=-1;
}
else if (key == KeyEvent.VK_W && walkUp == true)
{
Screen.movementY=1;
}
if (key == KeyEvent.VK_D && walkRight == false)
{
Screen.movementX =0;
}
else if (key == KeyEvent.VK_A && walkLeft == false)
{
Screen.movementX=0;
}
else if (key == KeyEvent.VK_S && walkDown == false)
{
Screen.movementY=0;
}
else if (key == KeyEvent.VK_W && walkUp == false)
{
Screen.movementY=0;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_D)
{
Screen.movementX=0;
}
else if (key == KeyEvent.VK_A)
{
Screen.movementX=0;
}
else if (key == KeyEvent.VK_S)
{
Screen.movementY=0;
}
else if (key == KeyEvent.VK_W)
{
Screen.movementY=0;
}
}
Collision:
public static void collision()
{
p.walkUp = true;
p.walkDown = true;
p.walkLeft = true;
p.walkRight = true;
for (int i = 0; i < wallTileArr.size(); i++)
{
wallTile = wallTileArr.get(i);
wallTile.collision(p);
}
}
And:
public void collision(Player p)
{
if (p.downGetBounds().intersects(getBounds()))
{
p.walkDown = false;
}
else if (p.upGetBounds().intersects(getBounds()))
{
p.walkUp = false;
}
else if (p.leftGetBounds().intersects(getBounds()))
{
p.walkLeft = false;
}
else if (p.rightGetBounds().intersects(getBounds()))
{
p.walkRight = false;
}
}
Switching JPanels (Using this for Main Menu etc)
public static void changePanelTo(Component add)
{
Main.f.getContentPane().invalidate();
Main.f.getContentPane().removeAll();
Main.f.add(add);
Main.f.validate();
add.requestFocusInWindow();
}
Feel free to ask questions regarding the code!
Download: Click Here
If You are using
java.util.Timerclass then watch here .It Clearly stays that:
So sometimes the TimerTask associated with your Timer class is fired on exact collision time but sometimes it takes a while because by that time your previous task might be completing..