I'm trying to write some code that causes a 2d ball to move around when the mouse gets near it, but it's not working. (I haven't been programming for very long..) Here is the current code:
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import acm.graphics.*;
import acm.program.*;
@SuppressWarnings("serial")
public class MoveAway extends GraphicsProgram implements MouseMotionListener {
static int width;
static int height;
int x = 100;
int y = 100;
GOval runaway;
public void main(){
System.out.println("Movement Detected");
System.out.println("Stop Moving!");
width = getSize().width;
height = getSize().height;
addMouseMotionListener(this);
}
public void run() {
System.out.println(width);
System.out.println(height);
GOval runaway = new GOval(50, 50);
runaway.setColor(Color.blue);
runaway.setFilled(true);
add(runaway);
runaway.setLocation(x, y);
}
public void mouseMoved(MouseEvent e) {
System.out.println("test");
if(x - e.getX() > -50 && y - e.getY() > -50) {
runaway.setLocation(x - 1, y - 1);
y = y - 1;
x = x - 1;
System.out.println("Close!");
}
if(x - e.getX() < 50 && y - e.getY() < 50){
runaway.setLocation(x + 1, y + 1);
y = y +1;
x = x - 1;
System.out.println("Close!");
}
}
}
Some of this (or most) may be super-beginner stuff that's really obvious, but I don't know how to do it.