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

2014/5/1

help with random spawn

nc-munk nc-munk

2014/5/1

#
I am making a game for a school project. I need help a random spawn function it is should spawn an asteroid in top for the screen and move down and i cant make them spawn and move my code look in line 27 to 42
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot) 

public class ScrollWorld extends World 
{ 
    private static final GreenfootImage bgImage = new GreenfootImage("space1.gif");
    private static final int scrollSpeed = -4;

    private GreenfootImage scrollingImage;
    private int scrollPosition = 0;
    private int startAsteroid = 1;
    public int pause = 10;

    public ScrollWorld()
    {
        super(400, 600, 1);

        GreenfootImage background = new GreenfootImage(400, 600);
        scrollingImage = getScrollingImage(400, 600);
        background.drawImage(scrollingImage, 0, 0);
        setBackground(background);

        addObject(new SpaceShip(), 200, 570);
        //addAsteroids(startAsteroid);
        prepare();
    }
    
    public void addAsteroid ()
    {
        Asteroid asteroid = new Asteroid();
        if (pause>0)
        {
            pause--;
            return;
        }
        if (pause ==0)
        {
            int x = Greenfoot.getRandomNumber(400);
            int y = (2);
            addObject(new Asteroid(), x, y);
            //asteroid.setRotation();
        }
    }
    
    public void act()
    {
        if(scrollSpeed < 0 && scrollPosition <= 0) 
        {
            scrollPosition = getHeight();
        }
        if(scrollSpeed < 0 && scrollPosition >= getHeight()) 
        {
            scrollPosition = 0;
        }
        scrollPosition -= scrollSpeed;
        paint(scrollPosition);
    }

    /**
     * Paint scrolling image at given position and make sure the rest of
     * the background is also painted with the same image.
     */
    private void paint(int position)
    {
        GreenfootImage bg = getBackground();
        bg.drawImage(scrollingImage, 0, position);
        bg.drawImage(scrollingImage, 0, position - scrollingImage.getWidth());
    }

    /**
     * Returns an image with the given dimensions.
     */
    private GreenfootImage getScrollingImage(int width, int height)
    {
        GreenfootImage image = new GreenfootImage(width, height);
        for(int x = 0; x < width; x += bgImage.getWidth()) 
        {
            for(int y = 0; y < height; y += bgImage.getHeight()) 
            {
                image.drawImage(bgImage, x, y);
            }
        }
        return image;
    } 

    /**
     * Prepare the world for the start of the program. That is: create the initial
     * objects and add them to the world.
     */
    private void prepare()
    {
    }
}
You need to login to post a reply.