Search code examples
androidarraylistspriterect

arraylist android tutorial?


So I created a class named Sprite. I want to be able to control many of the Sprite class easily and don't know how. I heard about arraylist but I don't know how to use it. I googled it many times and for a few days now I couldn't find a good easy tutorial. Basically I want to be able to create about 5 sprites and be able to check its collision. I am using a Rect to check the collision. this is how I check the collisions:

if(Rect.intersects(sprite.dst, floor))

it works but i want to control multiple sprites and check their collision and delete them if they collided. Any good tutorials or ideas ? please help. I hope I was clear enough about my question.. Thanks!

I found a way to do it but now i have a problem making a random y position for the sprite:

  public void rockUpdate(Canvas canvas){
    int y = rand.nextInt(canvas.getHeight()-doodle.getHeight()) + 1;
            int x =canvas.getWidth();

        rockSprites.add(new Sprite(GameSurface.this, doodle, 4, 1, x, y));
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        el++;

    }

Solution

  • You mean something like this?

    List<Sprite> spriteList = new ArrayList<Sprite>();
    
    spriteList.add(new Sprite());
    
    // (etc)
    
    List<Sprite> spriteListForLoop = new ArrayList<Sprite>(spriteList);
    for (Sprite sprite: spriteListForLoop)
    {
        if (Rect.intersects(sprite.dst, floor))
        {
            spriteList.remove(sprite);
        }
    }
    

    Something like that is very basic Java... you should be able to find it in any basic java tutorial. If this is for a game you'd probably be better off finding something more sophisticated though - like a method on the sprite object that checks for intersection for that specific Sprite every time the Sprite moves.