We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I have an object (say a tank) and it calls another objects as its part, say, a turret. Now, I need the turret object to quer the tank object and ask for its coordinates and I can't get whether it can be done at all.
This is my code:
class Tank {
constructor () {
this.location = createVector (windowWidth/2, windowHeight/2)
this.velocity = createVector (0,-2);
this.sizeW = 50;
this.sizeH = 100;
this.angle = 0;
this.turret1 = new Turret;
}
show () {
push ();
translate (this.location.x, this.location.y);
rotate (radians(this.angle));
rectMode (CENTER);
rect (0, 0, this.sizeW, this.sizeH);
pop();
this.turret1.show();
}
rot (angle) {
this.angle = this.angle + angle;
this.velocity.rotate (radians(angle));
println (this.angle);
}
moveForward () {
this.location.add(this.velocity);
}
getLocation () {
return this.location}
}
class Turret {
constructor () {
this.location = createVector (windowWidth/2, windowHeight/2);
}
// This method needs to talk to the Tank //
update () {
this.location = this.Tank.getLocation();
}
show () {
//update();
ellipse (this.location.x,this.location.y, 50,50);
}
}
Answers
You shouldn't do it that way.
Each class (and thus, each object) you write should be a self-contained thing. That is, if you have a tank that has many turrets, the turrets themselves should not need to ask the tank they are on anything, because this creates a dependent relationship between the turret and the tank, which means the turret is not self-contained.
What you can do, instead, is have the tank tell the turrets to be in a new location. The turrets can they do whatever a turret likes with that information (like update its location (or not! maybe your tank has dropped a stationary turret, and the turret itself knows that it is stationary!)).
Something like this:
thank you, everything is clear.