hmw
hmw

Reputation: 81

A collision check method works on a mac, but not on PC

So I am stumped. Here is my collision check method`

 public void checkCollision ()
  {
   for (int i = 0; i < bullets.size()-1; i ++)
{
  for (int j = 0; j < enemiesLaunched.size()-1; j++)
  {
    Rectangle temp = enemiesLaunched.get(j).getRectangle();
    Rectangle temp2 = bullets.get(i).getRectangle();
    `

    if (temp2.intersects (temp))
    {
      String str = bullets.get(i).getPath();

      // since the bullets are selective, the following code is to check
      // if the right bullets hit the right germs

      if (str.equals("oil gland.png")) // bullet is from oil gland
      {
        if (enemiesLaunched.get(j).getInfo().equals("highAcid"))
        {
         enemiesLaunched.get(j).setVisible(false);
         bullets.remove(i);
        }
      }
      else if (str.equals ("sweat gland.png"))
      {
        if (enemiesLaunched.get(j).getInfo().equals("lysozome"))
        {
         enemiesLaunched.get(j).setVisible(false);
         bullets.remove(i);
        }
      }
      else
      {
        if (enemiesLaunched.get(j).getInfo().equals("mucus"))
        {
         enemiesLaunched.get(j).setVisible(false);
         bullets.remove(i);
        }
      }

`

On my mac, it works exactly how I intended. However, on my PC, it does not. To make matters more baffling, I have implemented the same logic on games further along in the game, and it works just fine on both the mac and pc, any help would be greatly appreciated!

Upvotes: 0

Views: 113

Answers (3)

AlexS
AlexS

Reputation: 5345

I'd rather use for-loops like this if possible to ensure I don't have some wrong indexes due to typos or something:

List<Enemy> enemies = new ArrayList<Enemy>;
for (Enemy enemy : enemies) {
    ...
}

For example with this loop:

for (int i = 0; i < enemies.size()-1; ++i)

you will always leave the last "enemy" untouched.

And then, to be sure I'm not screwing up my Lists and iterations I would keep references to objects that need to be removed and would remove them afterwards, because I'm not sure what happens when removeing items from a collection while iterating over the same collection. The behaviour might be collectiontype and implementation (of the collection) specific.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109593

What tears attention is size()-1 - sure? But bullets.remove(i); certainly should be followed by --i; as otherwise the for-incrementing would skip the next bullet.

Optimized it would be by keeping get(i) and get(j) in their own variables.

Upvotes: 1

jbowes
jbowes

Reputation: 4150

How are you doing your time delta, and what is the velocity on the two objects? If your time delta is sufficiently large enough, you might not detect the collision as the two objects could have pass right through each other between checks. Have a look here for an explaination.

Upvotes: 2

Related Questions