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

2017/10/3

An endless stream of... Rocks.

Beamo Beamo

2017/10/3

#
Hi! To get straight to the point, I'm making a simple space shooter game and the actor "rock" is being placed endlessly even though I have set it so that it would only spawn if the variable "rockInterval" has finished it's decrease cycle and reached 0, in which it is then set back to a certain number. (I've tried making this number larger and smaller and the result seems to stay the same). Any help would be appreciated! Here's the code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class MyWorld here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class MyWorld extends World
{
    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    private int rockInterval=0;
    private int rockCooldown=50;
    public void act(){
        addRock();
    }
    public MyWorld()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 800, 1); 
        prepare();
        
    }
    private void prepare()
    {
        Ship ship = new Ship();
        addObject(ship,300,700);
        Ship shipr = getObjects(Ship.class).get(0);
        shipr.rotationReset();
        counter counter = new counter();
        addObject(counter,70,36);
    }
    public void addRock(){
        rock rock = new rock();
        int x = getWidth();
        if(rockInterval == 0)rockInterval--;{
            addObject(rock,Greenfoot.getRandomNumber(x),0);
            rockInterval = rockCooldown;
        }
    }
}
Super_Hippo Super_Hippo

2017/10/3

#
Look closely at line 39. If the rockInterval is 0, you decrease it by 1. Then you have a { } block which is always executing. You need to place 'rockInterval--;' one line above or use the -- in the condition like this:
public void addRock()
{
    if (--rockInterval == 0)
    {
        addObject(new Rock(), Greenfoot.getRandomNumber(getWidth()), 0);
        rockInterval = rockCooldown;
    }
}
(Class name 'rock' should start with R and not r. Same with the counter.) Btw, in your prepare method, you don't need to this shipr field, you can continue using ship, it's the same object.
Beamo Beamo

2017/10/3

#
OH! Thank you!!
You need to login to post a reply.