I’m having some trouble finding out how this works. I’m making a tetris game in java and am able to make the blocks and all but the collision detection method that i have currently is not always (actually very rarely) accurate (important in Tetris :D)
Here is how i do it:
From main class Main class
...
/**
* This method controlls all of the logic in the game. Determines if a new block needs to be created,
* if the falling statues of the block should be changed, if the block needs to be moved left or right, etc.
*
*/
public void update(){
boolean fallingBlockExists = false; // assume that there isn't one falling
for(Block b: blocks){
if(b.isFalling()){
for(Block other: blocks){
// first detect if the blocks have collided with eachother... if it has then stop the falling one
if(b.hasColliedWith(other, getBufferStrategy().getDrawGraphics())) b.isFalling(false);
}
}
if(b.isFalling()) fallingBlockExists = true; //if there is a falling block then theres no need to make more
}
if(blocks.size() == 0 || fallingBlockExists == false){
blocks.add(new Block(0 + (int)(Math.random() * xLIMIT)));
}
for(Block b: blocks){
if(leftPressed && !rightPressed && b.isFalling() && (b.getX() > 10)){
// can't have both pressed at the same time...
b.moveLeft();
}
if(rightPressed && !leftPressed && b.isFalling() && (b.getX() < xLIMIT)){
//can't have both pressed at the same time...
b.moveRight();
}
if(b.getY() >= yLIMIT) b.isFalling(false);
if(b.isFalling()) b.moveDown();
}
drawStuff();
try{Thread.sleep(50);}catch(Exception e){};
}
...
and in the block class
...
public boolean hasColliedWith(Block other, Graphics g){
Graphics2D g2D = (Graphics2D) g;
otherRect.setRect(other.getX(), other.getY(), other.getWidth(), other.getHeight());
return(g2D.hit((Rectangle)myRect, (Shape)otherRect, true));
}
...
I’ve also tried using the intersect() method from the rectangle class and had same results. Any help would be greatly appreciated…
Thanks :]