Classes and ArrayList
As a beginner in OOP, I tried to make a little traffic simulation
with cars and lorries. They shall learn to stop at the crossing, wait for
other vehicles and so on. Up to now I have this:
- A class Vehicle with methods to update position, accelerate or brake,
turn to left or right and and basic display method.
- Two subclasses LKW and PKW with different display methods (and later on
other additional methods), who inherit the vehicle methods.
That works well so far.
Now I added a class
Vehicle system to initialize an arraylist containing the LKW and PKW and later
on having methods to deal with the interaction of vehicles.
Now my Problem:
After starting the vehicle system with more than one vehicle, there are cars and lorries with different colors , but they are all displayed at the same position and their individual speed seems to add up.
What am I doing wrong?
Code:class Vehicle_System{
ArrayList vehicles;
int num;
Vehicle_System(int num){
this.num=num;
vehicles=new ArrayList();
PVector xx=new PVector(0,0);
PVector yy=new PVector(0,0);
color c=color(0,0,0);
for(int i=0;i<num;i++){
//initializing code
c=color(random(10,255),random(10,255),random(10,255));
if (random(0,1) < 0.5) {
xx.set(float(300+i*50),float(300),0);
//position
yy.set(random(1,2),0,0);
//speed
vehicles.add(new PKW(xx,yy,4.0,2.0,0.25*TWO_PI,c));
}
else {
xx.set(float(300),float(300),0);
yy.set(0,random(1,1.2),0);
vehicles.add(new LKW(xx,yy,2.5,1.5,0.50*TWO_PI,c));
//all vehicles get the same position-vector ort
// and the speed seems to add up, same for all.
//display and "abbiegen"="turn to ..." works separately.
//but speed and position???
}
}
}
void update(){
for(int i=0;i<vehicles.size();i++){
Vehicle v = (Vehicle) vehicles.get(i);
if(abs(v.ort.x-300)<1&&abs(v.ort.y-300)<1){
v.ort.x=300;
v.ort.y=300;
//get rid of rounding errors
v.abbiegen(ceil(random(0,2))*PI/2);
}
backgr();
v.update();
//update-method of class vehicle
v.display();
//display-method of subclass LKW or PKW
//seems to use the appropriate display-methods
//it displays LKW and PKW, not generic method
}
}
void backgr(){
background(100);
fill(0);
noStroke();
rect(300,300,600,60);
rect(300,300,60,600);
}
}