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

2012/5/19

Inheritance?

kartikitrak kartikitrak

2012/5/19

#
This is my current project setup. WorldClasses -SpaceWorld ActorClasses -Ship -Weapons -Pistol I have already setup my ship to be moved with the movement of the mouse, however the current issue is that I want the pistol objects to have the same x value as the ship object but I don't know to connect them. I want the code to be in the weapons subclass so that when I add more weapons I don't need to copy the code. I control the movement of the ship from the SpaceWorld class(subclass World) and I'm trying to get the x values of various weapons(from the weapons class) to have the same x value as the ship. SPACE WORLD
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class SpaceWorld extends World
{

    /**Variables*/
    private Ship playerShip = new Ship();

    private GreenfootSound LuxorEvolvedBossTheme = new GreenfootSound("LuxorEvolvedBossTheme.mp3");   

    public SpaceWorld()
    {    
        super(850, 650, 1, false);  //Create world that is 850x650 and has no borders               
    }

    public void act()
    {
        addObject(playerShip,425, 630);
        playMusic();
        playerMovement();
    }

    public void playerMovement()
    {   
        MouseInfo mouse = Greenfoot.getMouseInfo();

        if (mouse != null)
            playerShip.setLocation(mouse.getX(), 630); 

    }

    public void playMusic()
    {   
        LuxorEvolvedBossTheme.playLoop();      
    }
           
}
The other classes have literally nothing in them right now. Hope you can help me : D
danpost danpost

2012/5/19

#
You already have a reference to the 'playerShip' in the world class. You just need a way to pass it to another class by way of a method. Add to your sub-class of world,
public Ship getPlayerShip()
{
    return playerShip;
}
Now in the 'Weapons' class you can call the method above to get the reference, and use the dot operator to get its x-coordinate. You will be able to do this anywhere in the 'Weapons' class, except the constuctor(s) or any method that is called from the constructor(s). The call in the 'Weapons' class involves the following:
SpaceWorld sw = (SpaceWorld) getWorld();
setLocation(sw.getPlayerShip().getX(), getY());
which could also be coded
setLocation(((SpaceWorld) getWorld()).getPlayerShip().getX(), getY());
kartikitrak kartikitrak

2012/5/19

#
Thanks so much. Works fine.
You need to login to post a reply.