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

2017/3/11

I can't get my actor to spawn when run is clicked

S4uk0 S4uk0

2017/3/11

#
My code looks likes this:
import greenfoot.*;
import java.util.*;


public class You extends Actor
{
    private int DX = 3;
    private int DY = 3;
    private int x = getX();
    private int y = getY();
    public void act() 
    {
        moveAndCrouch();
        spawn();
    }     

    public void spawn()
    {
        Actor You = new You();
        getWorld().addObject(You, 400, 400);
    }

    public void moveAndCrouch()
    {
        if(Greenfoot.isKeyDown("right"))
            move(DX);
        if(Greenfoot.isKeyDown("left"))
            move(-DX);
        if(Greenfoot.isKeyDown("down"))
            setLocation(getX(), getY()+DY);
        if(Greenfoot.isKeyDown("up"))
            setLocation(getX(), getY()-DX);    
        if (Greenfoot.isKeyDown("j"))
        {
            setImage(new GreenfootImage("Swing 1.png"));
            Greenfoot.delay(2);
            setImage(new GreenfootImage("Swing 2.png"));
        }
        if(Greenfoot.isKeyDown("k")) 
        {   
            Actor myRock = new Rock();
            setImage(new GreenfootImage("Rock Throw.png"));
            getWorld().addObject(myRock, x+5, y);
        }

    }
}
Super_Hippo Super_Hippo

2017/3/11

#
Remove the 'spawn' method and add the You object from the world constructor. Right now, every You object creates another You object every act cycle. If there is none, then none will be created, but if there would be one, after one second, there would be so many that your computer could not handle them.
You need to login to post a reply.