/* Eyes.java by Shane Harper, Jan 2002 */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Eyes extends Applet implements MouseMotionListener { final int EYE_WIDTH = 50; final int EYE_HEIGHT = 65; final int EYE_SPACING = 5; Eye left, right; public void init() { addMouseMotionListener(this); left = new Eye((size().width-EYE_SPACING)/2-EYE_WIDTH, (size().height-EYE_HEIGHT)/2, EYE_WIDTH, EYE_HEIGHT); right = new Eye((size().width+EYE_SPACING)/2, (size().height-EYE_HEIGHT)/2, EYE_WIDTH, EYE_HEIGHT); } public void paint(Graphics g) { g.setColor(Color.blue); g.drawRect(0, 0, size().width-1, size().height-1); left.paint(g); right.paint(g); } public void mouseMoved(MouseEvent e) { Graphics g = getGraphics(); left.update(g, e.getX(), e.getY()); right.update(g, e.getX(), e.getY()); } public void mouseDragged(MouseEvent e) { mouseMoved(e); } } class Eye { final double IRIS_SIZE = 0.15; final double MAX_IRIS_DISPLACEMENT = 0.25; final double BORDER_SIZE = 0.1; int x, y; int width, height; int irisX, irisY; void paintIris(Graphics g) { final int iW = (int)(IRIS_SIZE*width); final int iH = (int)(IRIS_SIZE*height); g.fillOval(irisX-(iW/2) , irisY-(iH/2), iW, iH); } public void paint(Graphics g) { g.setColor(Color.black); g.fillOval(x, y, width, height); g.setColor(Color.white); g.fillOval(x+(int)(BORDER_SIZE*width), y+(int)(BORDER_SIZE*height), (int)((1.0 - 2*BORDER_SIZE)*width), (int)((1.0 - 2*BORDER_SIZE)*height)); g.setColor(Color.black); paintIris(g); } public void update(Graphics g, int mousePointerX, int mousePointerY) { g.setColor(Color.white); paintIris(g); final int centerX = x + (width/2); final int centerY = y + (height/2); // the x co-ordinate is scaled so that the eye is distorted to become // circular which simplifies the geometric calculation final int dX = (int)((mousePointerX - centerX) * (height/width)); final int dY = mousePointerY - centerY; final int dMousePointer = (int)(Math.sqrt( (dX*dX)+(dY*dY) )); final int dMaxDisp = (int)(MAX_IRIS_DISPLACEMENT*height); final float scale = (dMousePointer <= dMaxDisp) ? 1 : (float)dMaxDisp/dMousePointer; irisY = centerY + (int)(dY * scale); irisX = centerX + (int)(dX * scale * width/height); g.setColor(Color.black); paintIris(g); } public Eye(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; irisX = x + (width/2); irisY = y + (height/2); } }