Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Java Delayed Collision Detection

$
0
0
Hey!

I have a small problem regarding collision detection, you see... My detection is sometimes slightly delayed (30ms maybe?). Because of this delay the player can sometimes walk trough half of the wall and then gets stopped other times he stops at first contact (which is what I want all the time to happen) and sometimes he just walk right through the wall.

Code samples:

The KeyBoard input for the player (I believe that I have messed up some if/else statements here):

	public void keyPressed(KeyEvent e)
	{
		
		int key = e.getKeyCode();

			if (key == KeyEvent.VK_D && walkRight == true)
			{
				
					Screen.movementX=-2;
				
				
			}
			else if (key == KeyEvent.VK_A && walkLeft == true)
			{
	
					Screen.movementX=2;
				
					
				
			}
			else if (key == KeyEvent.VK_S && walkDown == true)
			{

					Screen.movementY=-2;
				
					
				
			}
			else if (key == KeyEvent.VK_W && walkUp == true)
			{

					Screen.movementY=2;
				
					
				
			}
			
			
			
			
			
			if (key == KeyEvent.VK_D && walkRight == false)
			{
				
					Screen.movementX=2;
				
				
			}
			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;
				
					
				
			}


		



	}

Collision loop:
		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);
			//System.out.println(p.walkDown);
		}


Collision code:

	public void collision(Player p)
	{
		if(getBounds().intersects(p.upGetBounds()))
		{
			
			p.walkUp = false;
			
		}
		else if(getBounds().intersects(p.downGetBounds()))
		{
			
			p.walkDown = false;
			
		}
		else if(getBounds().intersects(p.leftGetBounds()))
		{
			
			p.walkLeft = false;
			
		}
		else if(getBounds().intersects(p.rightGetBounds()))
		{
			
			p.walkRight = false;
			
		}
	}



I personally think the problem lies in either the loop or my if/else statements. And sometimes the code requires to be seen through different eyes(which is why I'm posting here) to see the problem. Searching for this on Google(Java Collision Delays) doesn't show up relevant posts (maybe I am using wrong keywords?).

Feel free to ask for more code samples!

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>