[Solved]Block Collision

I already know the problem, but I don’t know how to fix it.

So I have code, like this:


for (int i = 0; i < units.size(); i++) {
 Unit temp = units.get(i);
  for (int i2 = 0; i2 < blocks.size(); i2++) {
   if (temp.collisionCheck(temp2))
    temp.setFalling(false);
   else (!temp.collisionCheck(temp2))
    temp.setFalling(true);
  }
}

And if the player collides with a block, it would stop falling, and vice versa.
But, since it checks with each block,
it would be true that it collided with one block, but since it didn’t collide with the rest,
it would start falling again.

It’s very hard for me to solve this problem,
could somebody help? :slight_smile:
If you need more source code, I’ll provide a link.
And this is not the same problem as the “Rectangle.intersects” problem I had. :wink:

break;

break the loop when you find the block. Read up on java keywords.

Some flaws,

a) I see no temp2 assignment
b) the second IF is useless - remember what ELSE means
c) setting a boolean variable by IF-ELSE can be simplified like


temp.setFalling(!temp.collisionCheck(temp2));

I didn’t copy and paste the code, so instead I typed it quick:
a) it was to be:

Block temp2 = (Block) blocks.get();

b) it was to be:

if else(blah)

c) Thank you

I thought break only applied to while loops, and switch.
And also, since that code is in a while loop, I thought that it would break that loop with the for loop.
Anyways, thanks for the solution.


if else(blah)

is not valid syntax. I believe you are looking for


else if(blah)

but even with that your statement doesn’t need if after the else. Take this example:


boolean blah = true;
if(blah)
    System.out.println("Blah!");
else
    System.out.println("this is actually important...");

The else block will be run if blah equals false. Putting in an if after that is useless unless there are other variables involved. Also, break is used in for loops too.

@sugarrush break can be used with for loops also. If you have nested loops (a loop in a loop) you can break them by naming the loops and then breaking that (for example naming your outer loop ‘out’ so then you could do break ‘out’:wink: