Use variables from a class in an other class
in
Programming Questions
•
1 year ago
Hi !
I created a program/little game in which circles are falling from the top, and the player must avoid these circles by moving a pad (represented by a square).
I created three classes : one for the pad, an other for the circles, and an other that determines if a circle touches the pad.
I'd like to use variables from the class that contains the pad (like x and y positions) and from the one that contains the circles (x and y positions too) into my third class, so I could write something like "if the distance between the center of the circle is less than [width of the circle], the player looses one life".
Thing is, I don't understand how to "import" variables from one classe to another. I tried to write this :
- class Bang{
- float distance;
- Spaceship spaceShip;
- Monster monster1;
- Monster monster2;
- Monster monster3;
- Monster monster4;
- float Bang(){
- spaceShip = new Spaceship();
- monster1 = new Monster(color(60, 232, 49), random(125, 265), 0, 1);
- monster2 = new Monster(color(240, 146, 31), random(125, 265), 0, 2);
- monster3 = new Monster(color(18, 255, 253), random(125, 265), 0, 4);
- monster4 = new Monster(color(242, 95, 95), random(125, 265), 0, 6);
- distance = dist(xSps, ySps, xMstr, yMstr);
- return distance;
- }
- void boom(){
- if(distance<40){
- life--;
- }
- }
- }
(Spaceship is the name I gave to my pad, and Monsters is the name I gave to my circles falling from the top. ySps and xSps are the coordinates of the pad, and xMstr and yMstr the coordinates of the "monsters")
But it gives me this error message : the field Component.x is not visible. I guess it means the program doesn't find anything named "x" in the class, but I thought that by writing "Spaceship spaceShip; etc." before the constructor, it would also import the variables from those classes.
This is the first time I try to program something object oriented, I've searched solutions but I just don't understand how it works :-/
Thanks in advance !
PS : I'm French, my english may not be perfect.
1