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

2014/9/18

How do you make enemies shoot

coder04 coder04

2014/9/18

#
This is my enemy class which needs to shoot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import greenfoot.*;
 
public class Miniship extends Actor
{
    public void act()
    {
        move(4);
        randomTurn();
        turnAtEdge();
    }
     
    /**
     * With a 10% probability, turn a bit right or left.
     */
    public void randomTurn()
    {
        if ( Greenfoot.getRandomNumber(100) < 10 )
        {
            turn( Greenfoot.getRandomNumber(40)-20 );
        }       
    }
     
    /**
     * If we reach the edge of the world, turn a little bit.
     */
    public void turnAtEdge()
    {
        if (atWorldEdge())
        {
            turn(7);
        }
    }
    public boolean atWorldEdge() 
    
        if(getX() < 10 || getX() > getWorld().getWidth() - 10
            return true
        if(getY() < 10 || getY() > getWorld().getHeight() - 10
            return true
        else 
            return false
    }   
}
Super_Hippo Super_Hippo

2014/9/18

#
You will need a class which represents the bullet. You write a new method which adds a bullet object at the position of this Miniship with the same rotation (or with a fixed turn, depends on the images or if you want them to target you for example). Of course you should not add a bullet every act cycle, so you create a timer and let the Miniship only shoot when the timer reached a given value.
coder04 coder04

2014/9/18

#
i have got a shot class but i have got no code in it. i know how to make it kill me but i need to know how to spawn the bullet and shoot straight or target me.
Super_Hippo Super_Hippo

2014/9/18

#
Don't you also shoot with your ship? Then you should already know how to spawn the bullet. To set the rotation, you can give the 'Shot' class a parameter in the constructor and pass the rotation of the ship there. If you want it to target you, you can use the 'turnTowards' method. As an alternative, which I used in my Space Shooter scenario for the enemies which shoot at you, I calculated the rotation "by hand".
1
2
3
4
double x = Welt.schiff.getExactX()-getExactX();
double y = Welt.schiff.getExactY()-getExactY();
double s = Math.atan2(y,x);
s = Math.toDegrees(s);
('Welt' is the World class and 'schiff' is the public field which holds the ship object.) Then you can do something like
1
getWorld().addObject(new Shot( (int) s), getX(), getY() );
Or easier, just use 'turnTowards' instead. I am not 100% sure, but I guess this method isn't possible in the constructor, because it needs the position in the world. So you can use the 'addedToWorld' method to call this 'turnTowards' there.
You need to login to post a reply.