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

2015/12/13

Adding an enemy after food is eaten

supersmashmemes supersmashmemes

2015/12/13

#
Hey guys. I'm trying to make it so that when my spaceship eats a green dot, another red dot (which is the enemy) appears. I am doing this so that my game gets gradually harder with more and more red dots as you eat food. However, there is an issue. In the editor for my spaceship subclass (which is called "Player"), I have a method for eating green dots. That works fine. I tried to add "world.addObject(enemy);" into the method. I have already defined "world", so that is not an issue. It still doesn't work. Here is my code for the Player subclass:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Player here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Player extends Actor
{
    /**
     * Act - do whatever the Player wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if (Greenfoot.isKeyDown("up"))
        {
            move(4);
        
        
    }
    if (Greenfoot.isKeyDown("down"))
    {
        move(-4);
}
if (Greenfoot.isKeyDown("right"))
{
    turn(4);
}
if (Greenfoot.isKeyDown("left"))
{
    turn(-4);
    
}
Actor food;
        food = getOneObjectAtOffset(0, 0, Food.class);
        if (food != null)
        {
            World world;
            world = getWorld();
            world.removeObject(food);
            world.addObject(enemy);

            Greenfoot.playSound("eatfood.wav");
           
      
    }
  
}
}
supersmashmemes supersmashmemes

2015/12/13

#
I would also like to add that I do not yet have a random respawning method for green dots. I don't think that has anything to do with this, but I thought that might mean something in this issue.
danpost danpost

2015/12/13

#
'enemy', on line 43, is not defined; also, you do not give the coordinates at which to add the actor into the world at. You need to first create a new enemy object, then add it into the world at whatever coordinates you require (I will presume that it would be any random location):
World world = getWorld();
Enemy enemy = new Enemy();
int x = Greenfoot.getRandomNumber(world.getWidth());
int y = Greenfoot.getRandomNumber(world.getHeight());
world.addObject(enemy, x, y);
supersmashmemes supersmashmemes

2015/12/13

#
That helped! Thanks a lot!
You need to login to post a reply.