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

2015/11/13

Have object follow game

TheBrains1001 TheBrains1001

2015/11/13

#
I need to make this object follow the mouse at all times. Remove keyboard controls and ingnore other classes
import greenfoot.*;

/**
 * Write a description of class Ship here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Ship extends Actor
{
    private int canShoot = 0;
    private int lives = 3;
    /**;
     * 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() 
    {
        keyCommand();
        hitbox();
        if(lives == 0) 
        {
            getWorld().removeObject(this);
            Greenfoot.stop();
        }
    } 
    public void keyCommand()
    {
        if(Greenfoot.isKeyDown("up"))
        {
            up();
        }
        if(Greenfoot.isKeyDown("down"))
        {
            down();
        }
        if(Greenfoot.isKeyDown("left"))
        {
            left();
        }
        if(Greenfoot.isKeyDown("right"))
        {
            right();
        }
        if(Greenfoot.mousePressed(this) && (canShoot<=0))
        {
            fire();
            Greenfoot.playSound("pew.mp3");
            canShoot = 25;
        }
        canShoot--;
    }
    public void up()
    {
        setLocation(getX(),getY()-5);
    }
    public void down()
    {
       setLocation(getX(),getY()+5); 
    }
    public void left()
    {
        move(-5);
    }
    public void right()
    {
        move(5);
    }
    public void fire()
    {
        getWorld().addObject(new Missle(), getX(), getY());
    }
        private void respawn()
    {
        setLocation(getWorld().getWidth(), Greenfoot.getRandomNumber(200));
    }
    public void hitbox()
    {
        if(getOneIntersectingObject(Alien.class)!=null)
        {
            getWorld().addObject(new Explosion(), getX(),getY());
            Greenfoot.playSound("explosion.wav");
            Actor alien = getOneIntersectingObject(Alien.class);
            getWorld().addObject(new Ship(), Greenfoot.getRandomNumber(600), Greenfoot.getRandomNumber(400));
            getWorld().removeObject(this);
        }
        
    }
}
danpost danpost

2015/11/13

#
Removing keyboard control is as simple as re-creating the class in its entirety (remove it and add it back in to your project). I hate to sound like a broken record, but you should refer to the MouseInfo class API documentation to be able to determine the location of the mouse. The Actor class API documentation can be reviewed to find methods to do the actions required to follow the movements of the mouse.
You need to login to post a reply.