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

2021/6/1

Error while adding new objects on world

tayyabah72 tayyabah72

2021/6/1

#
I am trying to add objects in classes however when i am using the add object method its giving error but i have other programs which have exact same method and no error so i am not sure what i am doing wrong.Can someone please advise when you don't have any code in the classes and you are trying to add objects on world with the add object method then what do you need to make sure ?
danpost danpost

2021/6/1

#
tayyabah72 wrote...
I am trying to add objects in classes
If the object creating the object is not the active world, then you need a reference to the active world to call addObject on. You may have the following:
1
2
3
4
5
// in World subclass
addObject(new Ball(), 0, 0);
// where the above line is really
this.addObject(new Ball(), 0, 0);
// where 'this' refers to a World object
All instance (non-static) methods are executed on an object -- an instance of the class the class the method is in. That is, the following format holds: expressionGivingAnObject.methodName(); If no object is explicitly given, then, by default, it is implicitly assumed to be the same object that the calling method is being executed on (aka: 'this'). Since addObject is a World instance method, it must be executed on a World object. You can use the Actor instance getWorld method to get the World instance an actor is in:
1
2
3
4
// in Actor subclass instance method (with 'this' instance in world)
getWorld().addObject(new Ball(), 0, 0);
// or, equivalently
this.getWorld().addObject(new Ball(), 0, 0);
tayyabah72 tayyabah72

2021/6/2

#
I am trying to write code in the object classes to display the objects on the main world so in my example i have the cheeseworld and i am trying to add the mouse on cheeseworld so i am basically calling the mouse method in cheeseworld however i haven't made the code yet to add mouse so in that method would i be using addObject(new mouse(). 0,0); or do i need to add the getworld and where do i add that?
danpost danpost

2021/6/2

#
Sounds like you are trying to construct your world. That is, place the initial actors into your world. That would be coded in your World subclass, either in the constructor method or in a method called from that constructor (usually called prepare).
You need to login to post a reply.