Search code examples
arraysvectorappendprocessingpush-back

How to "push_back" in Processing


I am trying to create Space Invaders with Processing, and I am currently working on making the shooting mechanic. I have set up where when you press T, I will make a new variable called newBullet based off the class Bullets. I will say that it is moving up and is spawned, I then want to add this newBullet to an array called bulletsArray which is an array of the class Bullets. I have worked with arrays in c++ before and you can just call a push_Back function. It might be because in c++ I call this with vectors but I can't figure out how to make a vector in processing. I found a function called append and called it like this:bulletsArray = append(BulletsArray[], newBullet); but this doesn't work and gives me these errors:errors I don't know what this is complaining about and would really appreciate help. The website I am looking at is processing website on append(). Here is my code: my github code


Solution

  • If you wanted a c++ Vector, you will have an easier time working with an ArrayList than a normal array.

    To do this, you'll have to declare your arraylist like you did with your current array, but initialize it in the Setup() function.

    //Global declaration
    ArrayList<Bullets> bullets;
    
    //in the Setup() function
    ArrayList<Bullets> bullets = new ArrayList<Bullets>();
    

    ArrayLists are dynamic and easy to use, and they have a bunch of little tools which may help you later on. In your case, you'll want to add bullets and remove some:

    bullets.Add(New Bullets(....))
    bullets.Remove(i)
    

    Have fun!