|
Author |
Topic: Adding Objects to Arrays (Read 417 times) |
|
GotCool
|
Adding Objects to Arrays
« on: Aug 6th, 2004, 2:04am » |
|
I'm trying to add a Ball class to the Array "balls" every second. This is what I have (abriged): Code: Ball[] balls; void setup() { ... balls = new Ball[10]; newBall(); } ... int pS = 0; void loop() { int s = second(); print(s); if (pS != s) { newBall(); } int pS = s; ... } class Ball { ... } void newBall() { int i = balls.length; balls[i] = new Ball(); ... } |
| I'm pretty sure the problem is somewhere in there. Any help is appreciated. Also, if someone could explain Code: and Code: I got them from a tutorial but I can't figure what they do.
|
« Last Edit: Aug 6th, 2004, 2:05am by GotCool » |
|
|
|
|
sspboyd
|
Re: Adding Objects to Arrays
« Reply #1 on: Aug 6th, 2004, 9:05am » |
|
Im not quite sure what's going on with the newBall() stuff but I can tell you that your line, Code: declares that the variable 'balls' will be an array of objects created from your Ball class. And the other line, Code: basically means that the array called balls will have ten spaces for Ball objects. One other point, you probably don't want to be initalising the variable pS twice. Im guessing you only want to initalise it once at beginning to make it a global and then update the value (eg. take out the int before it in the void loop() ).
|
« Last Edit: Aug 6th, 2004, 9:11am by sspboyd » |
|
gmail.com w/ sspboyd username
|
|
|
fjen
|
Re: Adding Objects to Arrays
« Reply #2 on: Aug 6th, 2004, 10:32am » |
|
Quote:add a Ball class to the Array "balls" every second |
| the problem you're having is that arrays in java are not resizable on the fly. so the way to go is you have to enlarge your array for one position, then insert a new ball-object into there. see original post here: http://processing.org/discourse/yabb/board_Syntax_action_displa_y_num_1091061255.html or to get you started: Code: void addBall () { // temporary array Ball[] balls_temp = new Ball[balls.length+1]; // copy balls into temp array System.arraycopy(balls, 0, balls_temp, 0, balls.length); // insert new ball into highest position balls_temp[balls.length] = new Ball(); // set balls array to be temp array balls = balls_temp; } |
| btw. if you're adding a ball every second you might run into performance issues after some minutes (hours) ... consider to have it limited to a certain number of balls ...
|
« Last Edit: Aug 6th, 2004, 10:36am by fjen » |
|
|
|
|
|