Recently I have been playing around with basic 2D java game programming and have been having a lot of fun discovering things on my own, but I have come up with a problem. I have created a simple collision method that has been extremely buggy. So my question is how to change the x and y of the player when they collid with a block. I have tried the below code and it is recognizing when the player has collided but it doesn't set his x and y to the x and y to the tempx and y. Code:
private void update(){
tempx = player.getX();
tempy = player.getY();
collided = checkCollision();
if(collided == false){
player.update();
}
else if(collided){
player.setX((int)tempx);
player.setY((int)tempy);
System.out.println("COLLIDED");
}
}
private boolean checkCollision(){
for(int i = 0; i < tiles.size(); i++){
Tile t = tiles.get(i);
Rectangle tr = t.getBounds();
if(tr.intersects(player.getBounds())){
return tr.intersects(getBounds());
}
}
return false;
}
The collision is being detected but the player x and y aren't being changed accordingly. If you need more code or have any questions just ask. Thanks for any help:)
P.S. I have tried adding gravity and the collision only works for the top of the blocks if that is any help
Below is the player.update() method:
@Override
public void keyPressed(KeyEvent e){
int k = e.getKeyCode();
if(k != 0){
if(k == KeyEvent.VK_W){
y -= vy;
}
else if(k == KeyEvent.VK_A){
x -= vx;
}
else if(k == KeyEvent.VK_S){
y += vy;
}
else if(k == KeyEvent.VK_D){
x += vx;
}
}
}
public void update(){
}
The problem appears to be in your update method.
private void update(){
tempx = player.getX(); // tempx now is the same as the players x location
tempy = player.getY();
collided = checkCollision();
if(collided == false){
player.update();
}
else if(collided){
player.setX((int)tempx); // you set players location equal to temp, which is
player.setY((int)tempy); // already the players location
System.out.println("COLLIDED");
}
}
Since you are setting the players location equal to the location that it is currently in, you're not going to see the character move anywhere at all. You'll probably want to change the values of tempx
and tempy
tempx = player.getX() + 10;
tempy = player.getY() + 10;
Update
There seems to be some confusion about how the updating process is working.
Consider the following:
Given the above the following happens in your update method and IN THIS ORDER
tempx = player.getX()
both x's are now 0tempy = player.getY()
both y's are now 0You have to set tempx
and tempy
equal to the characters location outside of the update loop if you want them to remain the same throughout the characters updated movements.