When I tried coding the shot to go in the direction of the ship I made it so it keeps changing with the ship's direction. I just want its direction to be the ship's when it's fired not always changing. I know why it's happening but I don't know how to fix it.
the code of the ship is
and the shot's code is
I know the reason is that this code
is making the shot keep changing to the ships direction but I don't know how I can add it so it only does it once it's fired.
public class Rocket extends Actor { private int shotTimer = 0; public Rocket() { setImage("rocket.png"); getImage().scale(50, 35); turn(-90); } /** * Act - do whatever the Rocket wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (Greenfoot.isKeyDown("left")) { turn(-5); // delay next shot } if (Greenfoot.isKeyDown("right")) { turn(5); // delay next shot } if (Greenfoot.isKeyDown("up")) { move(4); // delay next shot } if (Greenfoot.isKeyDown("down")) { move(-4); // delay next shot } if (shotTimer > 0) { shotTimer = shotTimer - 1; } else if (Greenfoot.isKeyDown("space")) { getWorld().addObject(new Shot(this), getX(), getY()); shotTimer = 50; // delay next shot } } }
public void act() { Rocket rocket = (Rocket) getWorld().getObjects(Rocket.class).get(0); setRotation(rocket.getRotation()); move(5); if((this.getX() < 5 || this.getX() > this.getWorld().getWidth() - 5) && (this != null)) { this.getWorld().removeObject(this); return; } if((this.getY() < 5 || this.getY() > this.getWorld().getHeight() - 5) && (this != null)) { this.getWorld().removeObject(this); return; } Actor rock = getOneIntersectingObject(Asteroid.class); if (rock != null) { // We've hit an asteroid! hitAnAsteroid(); getWorld().removeObject(rock); getWorld().removeObject(this); } } private void hitAnAsteroid() { Space spaceWorld = (Space) getWorld(); Counter counter = spaceWorld.getCounter(); counter.bumpCount(5); } }
Rocket rocket = (Rocket) getWorld().getObjects(Rocket.class).get(0); setRotation(rocket.getRotation());