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

2013/6/9

How do I control an actor with the mouse?

bernhard bernhard

2013/6/9

#
I am quite new to Greenfoot and tried to do this game where you got to catch fruits with a basket. I want the player to be able to control the basket with the mouse and therefore tried this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
 
public class Basket extends Actor
{
 
private int x = 0;
 
 public void act()
    {
     x = MouseInfo.getX();
     setLocation(x, 880);
    }
 
}
but when I compile it gives me the following error: "non-static method getX() cannot be referenced from a static context" what am I doing wrong and how can I fix it?
Gevater_Tod4711 Gevater_Tod4711

2013/6/9

#
The problem is that the method getX() in mouse info is not static and so you need an instance of the class MouseInfo to use this method. Try it like this:
1
2
3
4
5
6
public void act() {
    MouseInfo mouse = Greenfoot.getMouseInfo();
    if (mouse != null) {
        setLocation(mouse.getX(), 880);
    }
}
bernhard bernhard

2013/6/9

#
That worked, thanks :)
You need to login to post a reply.