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

2015/1/23

Space invaders

MrGigglez MrGigglez

2015/1/23

#
Hi, im making a space invaders game and I need help. how do I get the bullet to move up. when I shoot the bullet goes sideways. This is my code
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
43
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
/**
 * Write a description of class Ship here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Ship extends Animal
{
    /**
     * Act - do whatever the Ship wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        checkKeyPress();
 
    }
    public void checkKeyPress()
    {
        if(Greenfoot.isKeyDown("Right"))
        {
            move(10);
 
        }
        else if (Greenfoot.isKeyDown("Left"))
        {
            move(-10);
        }
        else if ("space".equals(Greenfoot.getKey())) 
        
            fire();
        }
    }
 
    public void fire()
    {
        Bullet b = new Bullet();//makes the bullet
        b.setRotation(getRotation());//sets the rotation of the bullet to be the same as the ship's
        getWorld().addObject(b, getX(), getY());
    }
}
danpost danpost

2015/1/23

#
Your ship has a rotation of zero, which makes it move left and right with 'move(-10);' and 'move(10);'. By setting the rotation of the bullet to that of the ship, the bullets will also move left and right when using the 'move' method. If you want to use the 'move' method to move an object upward, that object must have a rotation of '270'. This may or may not have the unfortunate result in having your bullets flying sideways depending on the image used for them. There are several ways to avoid this. Re-post if help is needed in this regard.
You need to login to post a reply.