Search code examples
javaintegerintrectangles

How to get the last value that an integer had before a method were executed


I have two squares that moves around on the screen, both of the squares are from the same class (it's the same square that was drawn two times). I have already figured out how to do the collision detection between them so thats not a problem. The problem is that the squares can go through each other so I was thinking that I could make it so that when the squares hit each other they will teleport to the latest x and y position they were on before they collided. I have tried some things but non of them works. In my thread I have this code for now.

for(int i = 0; i < rectangles.size(); i++){
    Rectangle rect = (Rectangle) rectangles.get(i);
    x = rect.getXPos();
    y = rect.getYPos();
    checkRectCollisionAndMovement();
    for(int j = i + 1; j < rectangles.size(); j++){
        Rectangle rect2 = (Rectangle) rectangles.get(j);
        Rectangle r1 = rect.getBounds();
        Rectangle r2 = rect2.getBounds();
        if(r1.intersects(r2)){
            rect.setXPos(x);
            rect.setYPos(y);
        }
    }
}

How would I make it so that it gets the x and y position before they colided and not the one they had while they were colliding?

This is the checkCollisionAndMovement method

public void checkRectCollisionAndMovement(){
    for(int i = 0; i < rectangles.size(); i++){ 
        Rectangle rect = (Rectangle) rectangles.get(i);
        if(rect.getYPos() > 500){
            rect.setYPos(rect.getYPos() - .1);
        }
        if(rect.getYPos() < 500){
            rect.setYPos(rect.getYPos() + .1);
        }
        if(rect.getXPos() > 500){
            rect.setXPos(rect.getXPos() - .1);
        }
        if(rect.getXPos() < 500){
            rect.setXPos(rect.getXPos() + .1);
        }                   
        if(rect.isVisibe()){
            rect.move();
        }else{ 
            rect.remove(i);
        } 
    }   
}

Solution

  • You can either store all previous x,y positions in a list and traceback one step when there is a collision or Store only last co-ordinates in temporary variables. But as Duncan has mentioned I feel your new path should reflect along the axis orthogonal to the impact