• Java: All elements of array being updated instead of one

    MarkGrillo Member

    I’ve been staring at this and fiddling for hours, so any help would be appreciated.

    I am currently using 2 ‘for loops’ to cycle through my car and ice arrays looking for collisions in the AndEngine library for Android. When there is a collision however, I want the car to ‘slip (speed up), but unfortunately, all of the other car’s speeds are updated as well.

    The only solution I found that works is by using a while loop instead of an if statement for the collision detection, but then this doesn’t update the position of the sprite real time, and only updates it when it is out of collision. It works individually of the other sprites, but defeats the point of it speeding up when hitting the ice.

    Once again, I would appreciate any sort of help to this problem. Please find attached the relevant code:

    @Override
    protected void onManagedUpdate(float pSecondsElapsed) {
    
                    for (int i = 0; i < rManager.getInstance().carArray.length; i++)
                    {                       
                        for (int j = 0; j < rManager.getInstance().iceArray.length; j++)
                        {
                            if(this.getX() < (rManager.camera.getWidth() + this.getWidth())){
                                this.setPosition(this.getX() + (rManager.getInstance().carArray[i].getSpeed() + speedMod), this.getY());
                            } else {
                                this.setPosition(0 - this.getWidth(), this.getY());
                            }
    
                            if (rManager.getInstance().iceArray[j].getIceSprite().collidesWith(rManager.getInstance().carArray[i].getCarSprite()))
                            {
                                Log.e("log", "car collided with ice");
                                this.setPosition(this.getX() + (rManager.getInstance().carArray[i].getSpeed() + 2f), this.getY());
                            }
                        }
                    }               
    
    
                    super.onManagedUpdate(pSecondsElapsed);
            }
    
  • SapnaVishwas Member

    I’m not familiar with Android but I did do a lot of programming in C a long time ago.
    The only questionable discrepancies I see are these:

    Line 4:

    you use rManager.getInstance().carArray.length

    Line 6:

    rManager.getInstance().iceArray.length;

    You have arrays without indexes and then on line 15 is the first time I see an Indexes (I & j) for the array.

    rManager.getInstance().iceArray[j].getIceSprite().collidesWith(rManager.getInstance().carArray[i].getCarSprite
Viewing 1 reply thread
  • You must be logged in to reply to this topic.
en_USEnglish