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

2014/1/3

Need change direction of shooting

DaveFenste DaveFenste

2014/1/3

#
Hi I have another problem. When I have my Player1 he is still shooting right, but I need to shoot that direction which he is facing. For better understanding pic here . Here's my code.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Player1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Player1 extends Mover
{
    /**
     * Act - do whatever the Player1 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    private GreenfootImage left = new GreenfootImage("left.jpg");
    private GreenfootImage right= new GreenfootImage("right.jpg");
    private GreenfootImage up= new GreenfootImage("up.jpg");
    private GreenfootImage down= new GreenfootImage("down.jpg");

    
    public void act() 
    {
        
        if (Greenfoot.isKeyDown("right")) {
            move(5);
            setImage(right);
            
        }
        else if (Greenfoot.isKeyDown("left")) {
            move(-5);
            setImage(left);
        }
        else if (Greenfoot.isKeyDown("up")) {
            setLocation(getX(), getY()-5);
            setImage(up);
        }
        else if (Greenfoot.isKeyDown("down")) {
            setLocation(getX(), getY()+5);
            setImage(down);
        }
        if ("space".equals(Greenfoot.getKey()))  
        {  
            fire(); 
        } 
        
    } 
     public void fire() {
        Bullet bullet = new Bullet();  
        getWorld().addObject(bullet, getX(), getY()); 
        
        
    
    }
}
danpost danpost

2014/1/4

#
Since you can tell the direction your player is facing by the image that it has, you should be able to do this:
public void fire() {
    Bullet bullet = new Bullet();
    getWorld().addObject(bullet, getX(), getY());
    if (getImage().equals(left)) bullet.setRotation(180);
    else if (getImage().equals(down)) bullet.setRotation(90);
    else if (getImage().equals(up)) bullet.setRotation(270);
    else bullet.setRotation(0);
}
Since you are not setting the image of the player to 'right' to start with (although it may be a different instance of the same image), I left that one as the final else. I am presuming that you are having the player face right to begin with.
You need to login to post a reply.