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

2018/5/23

Adding Actor object to world through an actor isn't working

YoureNotCute YoureNotCute

2018/5/23

#
I'm trying to make my Player class add a Bullet object whenever I click the mouse when it's on screen. But when I run the code, clicking doesn't seem to do anything. Any help would be appreciated! Thanks in advance. Here's my Player class. Character is an abstract class that extends Actor
public class Player extends Character
{
    private MouseInfo mouse = Greenfoot.getMouseInfo();
    private int money;
    public Player (int hp, int dmg, int spd)
    {
        super(hp, dmg, spd);
        money = 0;
    }
    public void move()
    {
        int x = this.getX();
        int y = this.getY();
        if(Greenfoot.isKeyDown("A")) {
            x-=5;
            this.setImage("playerLeft.png");
        }
        if(Greenfoot.isKeyDown("S")) {
            y+=5;
            this.setImage("player.png");
        }
        if(Greenfoot.isKeyDown("W")) {
            y-=5;
            this.setImage("playerForward.png");
        }
        if(Greenfoot.isKeyDown("D")) {
            x+=5;
            this.setImage("playerRight.png");
        }
        this.setLocation(x,y);
        charX=x;
        charY=y;
    }
    public void attack(){
        if(mouse!=null&&mouse.getButton()==1/*&&!Greenfoot.mouseClicked(shop object idk)*/){    
            Bullet bullet = new Bullet(mouse.getX(),mouse.getY());
            getWorld().addObject(bullet,this.getX(),this.getY());
        }
    }
}
Bullet class :
public class Bullet extends Actor
{
    private int turnX, turnY;
    public Bullet(int x, int y) {
        turnX = x;
        turnY = y;
        this.turnTowards(turnX,turnY);
        this.setImage("bullet.png");
    }
    public void act()  {
        move();
    }
    public void move()
    {
        if(!hitEnemy()) {
            super.move(10);
        }
    }
    public boolean hitEnemy() {
        return false;
    } 
}
danpost danpost

2018/5/23

#
YoureNotCute wrote...
I'm trying to make my Player class add a Bullet object whenever I click the mouse when it's on screen. But when I run the code, clicking doesn't seem to do anything.
Remove line 3 in the Payer class and continue from there. Line 3 will not update automatically every act step (get it first thing in attack method).
You need to login to post a reply.