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

2017/7/28

addobject problem

SwarmDark SwarmDark

2017/7/28

#
Greetings, I have recently been tasked with creating a game for my school project. This is my first time using java, and as an extension, Green foot. I have been trying to make a reaction game based on pressing buttons in combinations to create spells. However, I have been having problems with the objects and spells being added into the game. I have tried the addObject() method both in the world and my protagonists actor class, to no avail. I can also see the code somewhat working, as some of the objects pop up after i stop the game running. import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) public class Space extends World { public Space(){ super(900,700,1); orbs(); } public void orbs(){ Exort exort = new Exort(); addObject(exort, 400,400); String pressed = Greenfoot.getKey(); if( "z".equals(pressed)){ Quas a = new Quas(); addObject(a,400,400); } if("x".equals(pressed)){ Wex b = new Wex(); addObject(b,400,400); } if("c".equals(pressed)){ Exort c = new Exort(); addObject(c,400,400); } } } As you can see above I have tested to see if the actor will even be added to the world: Exort exort = new Exort(); addObject(exort, 400,400); and it worked, but for some reason it doesn't work when i try to create actors by pressing keys. Here is the actor classes that I am trying to create. import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) public class Wex extends Mover { public void act(){ } public void addedToWorld(World Space){ if(isTouching(Wex.class)){ int x = getX() +100; int y= getY(); setLocation(x,y); } } } the other actors(Quas and Exort) are just duplicates of this one. Any help would be much appreciated.
Super_Hippo Super_Hippo

2017/7/28

#
The constructor of an object is only executed once when the object is created. In your case, the 'Space()' method is executed once when your world is created. To check for key presses while the scenario is running, you need create the act method in your world class. This method will be called for the active world and all objects in that world, again and again.
public void act()
{
    String pressed = Greenfoot.getKey();
    //and so on
}
Using the 'getKey' method in a different context than writing text can create other issues though.
You need to login to post a reply.