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

2017/10/25

I cant get enemy to shoot back at oponents

pzb0024 pzb0024

2017/10/25

#
I have set up my enemy class to shoot at random with the intent to have them shoot at the opponent, however they are shooting in the direction they are drifting. Would anyone know how to correct that? here is the code for the enemy and its bullet subclass.
public class Enemy extends Actor
{
    private GreenfootImage left = new GreenfootImage("Enemy.png");
    private GreenfootImage right= new GreenfootImage("Enemy.png");
    private GreenfootImage up= new GreenfootImage("Enemy.png");
    

    public void act() { 
         setLocation(getX(), getY() - 1);
         move(-1/2);
         if (Greenfoot.getRandomNumber(100) < 5) {
            getWorld().addObject(new Bullet(getRotation()), getX(), getY());
         }
         move(1);
         if (Greenfoot.getRandomNumber(100) < 1) {
            setImage(right);
            move(-1);
         }
         
         if (Greenfoot.getRandomNumber(100) < 1) {
             setImage(left);
             move(1);
           
          }  
     }     

    // this is not yet working
    
     public void explosion() {
         Actor bullet = getOneIntersectingObject(Bullet.class); 
         if (bullet != null) {// is bullet there
             getWorld().removeObject(bullet); // remove bullet
             getWorld().removeObject(this); // remove enemy
         }  
    }
}



[code]public class EnemyBullet extends Enemy {
    private int direction, speed;
    
    // Can't get bullets to fly towards oponent!
    
    public EnemyBullet(int dir) {
        direction = dir;
        speed = -25;
    }  
    /**
     * Act - do whatever the EnemyBullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        setRotation(direction -1);
        move(speed);
    }    
}
danpost danpost

2017/10/25

#
Your Enemy actors are not turning -- that is, their rotation is always zero. So, passing 'getRotation()' for the direction of a new Bullet object does not make any sense. There are a couple other anomalies in your code. Line 10 appears to do nothing. Line 55 adjusts the direction of a bullet one degree left for no apparent reason. All your speeds (for both the enemies and the bullets) are negative values which is counter-intuitive. As far as the direction of the bullets, you need to use 'turnToward' with the coordinates of the opponent (or calculate, using trig functions, the angle of rotation required for the bullet objects) when they are created.
You need to login to post a reply.