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

2018/4/25

Game ends after shooting one enemy

nescafe nescafe

2018/4/25

#
I have a shooter game in which an actor (hero) shoots at enemies and keeps a score. Everything works fine except when the actor shoots at the enemy. I'm having issues with the score counting, and the game pausing. Any suggestions on how I can fix this? here's the enemy code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class enemy1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class enemy1 extends Actor

{
    int bulletStep=0;
    int point = 0;
    private int size;

    
    /**
     * Act - do whatever the enemy1 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public void act() 
    {
        
        detectCollision();
        setRotation(270);
        
         if (isAtEdge() ) 
        {
            move(1);
            setRotation(270);
        }

    }    
   
public enemy1()
{
    GreenfootImage image = getImage();
    image.scale(image.getWidth() - 1000, image.getHeight() - 1000);
    setImage(image);
}


    

public boolean tooNear()
{
    return !getObjectsInRange(100, Hero.class).isEmpty(); 
}
 
    
    private void updatePoint()
    {
        point++;
        getWorld().showText("Score :"+point,60, 10);
    }
    //adds a point when an enemy is shot
     private void detectCollision()
    {
        if(isTouching(Bullet.class))
        {
            removeTouching(Bullet.class);
            updatePoint();
            checkLast();
            getWorld().removeObject(this);
        }
    }


private void checkLast()
    {
        if(point==8)
        {
            getWorld().showText("Finish Score "+point,getWorld().getWidth()/2, getWorld().getHeight()/2); 
            Greenfoot.stop();
        }
    }
    
}
danpost danpost

2018/4/25

#
Move line 26 to the constructor (no need in continuous setting the same rotation to the actor). For line 27, use this:
if (getWorld() == null) return;
This is so that if detectCollisionremoves the actor from the world, isAtEdge won't error. The added statement uses a return statement to forces an immediate stop to the execution of the method if the actor is no longer in the world.
You need to login to post a reply.