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

2011/9/29

Non-Static method cannot be referenced from a static context

Duta Duta

2011/9/29

#
So basically I'm making Space Invaders (because I just made Pong so I decided to make another arcade game), and I'm getting this error. I have this code in my class for the bullet the spaceship (that you control) fires.
public class Bullet extends MyActors
{
    public void act() 
    {
        if(Greenfoot.isKeyDown("space")) {
            fire();
        }
    }
    
    public void fire()
    {
        Space.addObject(new Bullet(), (Spaceship.getX()), (Spaceship.getY()));
    }
}
When I try to compile, I get the error message:
Non-Static method getX() cannot be referenced from a static context
How do I get around this? (Space is my World, and Spaceship is... well my spaceship). The reason I'm doing this is because the bullet then starts at the spaceship and then (once I code it) it will move upwards until it hits the enemies. Lol I feel retarded, this is such a simple problem but my brains dead :/
Duta Duta

2011/9/29

#
Changed the fire() method to this but still no luck:
public void fire()
    {
        int x = Spaceship.getX();
        int y = Spaceship.getY();
        
        getWorld().addObject(new Bullet(), x, y);
    }
kiarocks kiarocks

2011/9/29

#
one, you will either 1) get a Null Pointer Exception or 2) not be able to fire unless there is already a bullet there. So to fix this, put the act code and fire method into the spaceship class.
actinium actinium

2011/9/29

#
If space is your world subclass then maybe Space s = (Space)getWorld(); then use public void fire() { s.addObject(new Bullet(), (Spaceship.getX()), (Spaceship.getY())); } maybe, not sure, im new
Duta Duta

2011/9/29

#
I've removed that code from the bullet class, and put it in the space class. The code is now:
public void addBullets()
    {
        int x = Spaceship.getX();
        int y = Spaceship.getY();

        addObject(new Bullet(), x, y);
    }
And obviously I changed the bullet classes act method to call Space.addBullets() rather than fire() Still no luck (although I didn't expect it to come with this change... I can't remember how to do this and its really frustrating me because I have done it before). Btw don't think I'm just sitting around until I can fix this - I've done a lot of other coding for the Space Invaders game while I've been waiting to either figure it out or someone to post and explain.
Duta Duta

2011/9/29

#
Oops, hadn't noticed the replies. I will try kiarocks approach (and if that doesn't work I'll try actiniums, although I don't see how that would make it work)
Duta Duta

2011/9/29

#
Thanks kiarocks, that worked. I have no idea why I didn't think of that before >.<
kiarocks kiarocks

2011/9/29

#
you're welcome
You need to login to post a reply.