Skip to content

Instantly share code, notes, and snippets.

@tjhancocks
Created May 22, 2012 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjhancocks/2768486 to your computer and use it in GitHub Desktop.
Save tjhancocks/2768486 to your computer and use it in GitHub Desktop.
Circular Motion Direction Detection
import java.awt.*;
import java.awt.event.*;
public class CircleDetector extends Frame implements MouseMotionListener {
private Label direction = null;
// These two variables help us detect the direction and circular motion.
private double lastAngle = 0;
private boolean antiClockwise = true;
public static void main(String[] args) {
new CircleDetector();
}
public CircleDetector() {
super( "Circle Detector" );
this.setSize( 300, 300 );
this.direction = new Label("Anti Clockwise");
this.add( this.direction );
this.addMouseMotionListener( this );
this.setVisible(true);
}
/*!
Mouse Motion Events
*/
public void mouseMoved( MouseEvent e ) {}
public void mouseDragged( MouseEvent e ) {
// Work out the current angle - first we work out the length of the line
// between two points. The window is locked at 300 by 300, so fix the point
// at 150, 150.
double dx = 150.0 - e.getX();
double dy = 150.0 - e.getY();
// Now we can work out the arctanget of the line. This is given in radians.
double angle = Math.atan2( dy, dx );
// Now check against the last angle and see what is happening.
if ( this.lastAngle < angle ) {
// We're going clockwise
this.direction.setText("Clockwise");
}
else if ( this.lastAngle > angle ) {
// We're going anti clockwise.
this.direction.setText("Anti Clockwise");
}
else {
// We're somehow standing still, yet moving.
// This can happen if the mouse is moving in a straight line to the center point.
this.direction.setText("Undefined");
}
this.lastAngle = angle;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment