We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Dynamically creating instances
Page Index Toggle Pages: 1
Dynamically creating instances (Read 435 times)
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
Re: Dynamically creating instances
Reply #1 - Dec 29th, 2005, 6:08am
 
Of course it was going to happen, as soon as I give in and write a question I find a nice solution already written.


http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1091750693

Page Index Toggle Pages: 1