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

2014/11/9

Help Shooting Please!

JamesHughes JamesHughes

2014/11/9

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Player extends Actor
{
    
    private GreenfootImage left = new GreenfootImage("Tank left.png");  
private GreenfootImage right= new GreenfootImage("Tank right.png"); 
   
  public void act()   
{  
    if (Greenfoot.isKeyDown("right"))  
    {  
        move(4);  
        if (getImage()!=right) setImage(right);  
    }  
    if (Greenfoot.isKeyDown("left"))  
    {  
        move(-4);  
        if (getImage()!=left) setImage(left);  
    }  
}  
}
Hi, i want my tank (above) to shoot an actor called Bullet horozontaly in the direction that it is going. The bullets image file is "Bullet.png". Thanks! :)
Super_Hippo Super_Hippo

2014/11/9

#
When the specified key is pressed, add the Bullet to the world at the current coordinates and pass the rotation.
getWorld().addObject(new Bullet(getRotation), getX(), getY());
And in the Bullet class you have something like this:
public Bullet(int rot)
{
    setRotation(rot);
    setImage("Bullet.png");
}

public void act()
{
    move(8);
    //check for intersecting objects or being outside (or at the edge) of the world and remove it then
}
danpost danpost

2014/11/9

#
The only thing you have to distinguish between a right or left facing tank is the image; so that will be the condition to use to determine the direction of the bullet:
Bullet bullet = new Bullet();
if (getImage() == left) bullet.setRotation(180);
setLocation(getX(), getY()+/* adjust height */); // if needed
move(/* adjust to end of muzzle */) // if desired
Now, this code needs to be within an 'if' block whose condition determines that tank is firing:
if (firing())
where you write a method to return a boolean value (true or false):
private boolean firing()
{
    boolean fire = false;
    /* some code that may change the value of 'fire' */
    return fire;
}
The code you use to possibly change the value of 'fire' would be checks on conditions or events that you decide you wish to use to determine the firing status. This could be a keyboard event, mouse event, or a continuously timed cycle.
You need to login to post a reply.