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

2017/5/20

How can i spawn an actor from another actor

Lucius Lucius

2017/5/20

#
Hey, i have a Problem with an actor wich should spawn another Actor
1
2
3
4
5
6
if("left".equals(Greenfoot.getKey()))
{setRotation(0);
Normalbullet normalbullet = new Normalbullet();
getWorld().addObject(normalbullet, getX(), getY());
normalbullet.setRotation(getRotation());
}}}
why dose it not work?
FutureCoder FutureCoder

2017/5/20

#
it's not working because you can't just use normalbullet.setRotation(getRotation()); to get the rotation. the line you need is
1
getWorld().addObject(new Normalbullet(getRotation()), getX(), getY());
but you also need to set up a number of variable in the normalbullet class and take these variables from that class and use them in the actor class, it's can be a complicated process. first use this in normabullet class.
1
2
3
4
5
6
private int direction, speed;
    public Normalbullet(int dir)
    {
        direction=dir;
        speed=15;
    }
then in the public void act use this
1
2
setRotation(direction);
        move(speed);
and finally in normalbullet class
1
2
3
4
5
6
private (name of actor that adds bullet)player;
    public shot((name of actor that adds bullet) player)
    {
      
     this.player=player;
    }
i think thats everything, if it doesn't work then maybe i missed something, but it should work
danpost danpost

2017/5/20

#
Lucius wrote...
Hey, i have a Problem with an actor wich should spawn another Actor <Code Omitted > why dose it not work?
Probably because you are using 'getKey'. If that object or one of your other objects (including the currently active World object) is using 'getKey' for some other purpose during the same action steps, then 'getKey' will work only for one of them. Use a combination of a boolean key state field and the 'isKeyDown' method:
1
2
3
4
5
6
7
8
9
10
11
12
// instance field
private boolean leftDown;
 
// in act method or in a method called by the act method
if (leftDown != Greenfoot.isKeyDown("left")) // change in state of "left" key?
{
    leftDown = !leftDown; // record change
    if (leftDown) // change was pressing (not releasing)?
    {
        // spawn code here
    }
}
Yehuda Yehuda

2017/5/21

#
FutureCoder wrote...
it's not working because you can't just use normalbullet.setRotation(getRotation()); to get the rotation.
That's not really true, if the setRotation method is public in Actor then it can be called on any instance of Actor. If NormalBullet is an extension of Actor then technically the following will work on it also:
1
2
3
Actor anActor = new Actor(){
};
anActor.setRotation(0);
There are methods which you can't call like this since they are 'protected' methods in class greenfoot.Actor as opposed to 'public'.
You need to login to post a reply.