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

2022/10/7

how can I add selected actor in another world?

Guy68 Guy68

2022/10/7

#
Hello, i have a problem, i wrote a code that is suppsed to work, but i cant find my mistake. I have a caracter on name:man in the World:Home, and when I click on the caracter:man I want the game to take me to world:MyWorld and I want the character man to appear there. My code is here: public void act() { if(Greenfoot.mouseClicked(this)){addedToWorld();} } public void addedToWorld() { World MyWorld = new MyWorld(); Greenfoot.setWorld(new MyWorld()); getWorld().addObject(new man(),200,330); } The game sends me to the wolrd:MyWorld but the caracter:man wont apear there. Can u help me with the problem? I would be thankful.
danpost danpost

2022/10/8

#
Guy68 wrote...
public void act()
    {
        if(Greenfoot.mouseClicked(this)){addedToWorld();}
    }
    public void addedToWorld()
    {  World MyWorld = new MyWorld();
       Greenfoot.setWorld(new MyWorld());
       getWorld().addObject(new man(),200,330);
    }
On last line (line 8), getWorld() should be MyWorld (the name you gave the MyWorld object you created two lines earlier) Using getWorld, you are getting the world of the actor whose act method is currently being executed for. That is not the world you want to add the man to.
Spock47 Spock47

2022/10/8

#
Additionally to what @danpost said, in line before that (line 7), instead of `new MyWorld()` again it has to be `MyWorld`. `new MyWorld()` creates a completely new world, therefore in your current version, you create one world in line 6 and then a second world in line 7. But what you actually want to do is to use the world created in line 6 in lines 7 and 8. Very helpful knowledge is to understand the difference between an object and a class. Here are some explanations about it: https://stackoverflow.com/questions/1215881/the-difference-between-classes-objects-and-instances https://www.geeksforgeeks.org/difference-between-class-and-object/ https://www.tutorialspoint.com/java/java_object_classes.htm
Guy68 Guy68

2022/10/8

#
Hello, so i still have the problem if i do what did u sad that i use MyWorld insted of new MyWorld() befor line 7 the game says that the MyWorld is undeclarated in the line 7 Or can u actualy type the right code, and n that cas i can understand where i have mistakes
Guy68 Guy68

2022/10/8

#
The problem is solved!!!! Thank you sooo much for your help!!
You need to login to post a reply.