This site requires JavaScript, please enable it in your browser!
Greenfoot back
johnmineur
johnmineur wrote ...

2014/4/13

Problems accessing a variable from an instance of a class

johnmineur johnmineur

2014/4/13

#
Hello... I have a world that contains many classes. Two of the classes are Photons and Asteroids. There are many instances of asteroids on the screen at any one time. Asteroids differ in size. An asteroid has an int variable called asteroidSize which I need to pass to the photon that hits it. I have successfully added counters to the game using constructors but have no idea how to 'target' one asteroid and return its information. Any help here would be much appreciated.
danpost danpost

2014/4/13

#
'getOneIntersectingObject' will return an object of given type that is currently colliding with the actor. Just typecast the returned object (fron the Photons class) to that of an Asteroids, check that it is not 'null' and then get the value of the field from it. If the field has private access, you will need to write and call a method to return its value.
johnmineur johnmineur

2014/4/13

#
Thanks for the help but I am very new to this and have become a little lost... I have pasted a section of the code I have within the Act() method of Photon below: if(canSee(Asteroid.class) && isActive==true) { Actor asteroid = getOneIntersectingObject(Asteroid.class); int_test = xxx.getAsteroidClass(); //The Asteroid class method that returns value //I am unsure what to do here :) counter.addPoints(5); eat(Asteroid.class); Greenfoot.playSound("Qqexplosion.wav"); isActive = false; }
danpost danpost

2014/4/13

#
If the 'asteroidSize' field is 'public', then the following would do:
int size = asteroid.asteroidSize;
If not, then you need to add a 'get' method to the Asteroid class:
public int getAsteroidSize()
{
    return asteroidSize;
}
and use
int size = asteroid.getAsteroidSize();
Either way, your line above that gets the asteroid:
Actor asteroid = getOneIntersectingObject(Asteroid.class);
is not sufficient to get the field value or use the method because these two items are not in the Actor class, but in the Asteroid class (see first word in the line). To access the field or method in the Asteroid class, you need to use:
Asteroid asteroid = (Asteroid) getOneIntersectingObject(Asteroid.class);
johnmineur johnmineur

2014/4/13

#
Hello again... just got back. Thank you very much for everything. You and people like you put so much time into projects like this. I hope I will be able to do the same in the future :)
You need to login to post a reply.