timmy_b
YaBB Newbies
Offline
Posts: 7
Dynamically creating instances
Dec 29th , 2005, 5:23am
Hi, I think that this is probably a relatively simple problem, but I have searched the site and for all the trying can't seem to get my head around this. I am relatively new to OOP but I have been working hard to understand the concepts and structure behind it!! All I want to do is to be able to dynamically instantiate new objects as the program is running, say on a mouse click or a key pressed. I realise that you can't add to Array objects and you have to either use a java class like vector or create a new array and copy the old one across, but I don't think I need to address this problem just yet. how, for example, could I create a new Ball object on a key press while the program, and then run its plot and move method continually. Ball[] balls; void setup(){ size(400,400); background(0); smooth(); balls = new Ball[10]; for(int i=0; i< balls.length; i++) { balls[i] = new Ball(100, 100, 20); } } void draw(){ background(0); for(int i=0; i<balls.length; i++) { balls[i].plot(); balls[i].move(); } } class Ball { int x; int y; int r; //actually the diameter int xDir; int xSpeed; Ball(int x_, int y_, int r_) { this.x = x_; this.y = y_; this.r = r_; this.xDir = int(random(10)); this.xSpeed = 1; } void plot(){ ellipse(x,y,r,r); } void move(){ x += (xDir * xSpeed); if(x > 400){ xDir *= -1; } if(x < 0){ xDir *= -1; } } } This above code works fine, I just can't dynamically add balls to it! Even if I created a blank Ball in the setup, and just didn't call the plot and move functions until a keyPressed function, I could not get this ball to behave like the others. It appears on the screen while I am holding a key, but it doesn't move. Thanks for any help, and I hope I have explained myself relatively clearly. In order for this to be of any use I know I will have to use arrays to store the new Balls and this sort of thing, but I was hoping to get even half way there first! tim