View Single Post
  #4 (permalink)  
Old 01-08-2008, 12:05 AM
hardwired hardwired is online now
Senior Member
 
Join Date: Jul 2007
Posts: 1,144
hardwired is on a distinguished road
Hyduken on street fighter.
I didn't find an example of this so used two balls (trying to get two balls to more around inside the larger ball) to illustrate one way you could approach this.
Code:
import java.awt.*; import java.awt.geom.*; import javax.swing.*; public class SpinTest extends JPanel implements Runnable { double cx = 140, cy = 140; Ellipse2D.Double green = new Ellipse2D.Double(cx-50,cy-50,100,100); Ellipse2D.Double red = new Ellipse2D.Double(cx-20,cy-50,40,40); Ellipse2D.Double blue = new Ellipse2D.Double(cx-20,cy+10,40,40); Shape[] shapes = { green, red, blue }; double xLoc = 0; int dx = 2; double theta = 0; double thetaInc = Math.toRadians(3); long delay = 100; protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.red); g2.draw(shapes[1]); g2.setPaint(Color.blue); g2.draw(shapes[2]); g2.setPaint(Color.green.darker()); g2.draw(shapes[0]); g2.setPaint(Color.magenta); Point2D.Double p = getCenter(shapes[0]); g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4)); } public void run() { boolean move = true; while(move) { try { Thread.sleep(delay); } catch(InterruptedException e) { move = false; System.out.println("interrupted"); } advance(); } } private void advance() { checkBoundries(); xLoc += dx; AffineTransform at = AffineTransform.getTranslateInstance(xLoc,0); shapes[0] = at.createTransformedShape(green); theta += thetaInc; Point2D.Double mp = getCenter(shapes[0]); Point2D.Double p = getCenter(red); double x = mp.x - p.x; //double y = mp.y - p.y; at = AffineTransform.getTranslateInstance(x, 0); at.rotate(theta, cx, cy); shapes[1] = at.createTransformedShape(red); shapes[2] = at.createTransformedShape(blue); repaint(); } private Point2D.Double getCenter(Shape s) { Point2D.Double p = new Point2D.Double(); Rectangle r = s.getBounds(); p.x = r.getCenterX(); p.y = r.getCenterY(); return p; } private void checkBoundries() { Rectangle r = shapes[0].getBounds(); if(r.x + dx < 0 || r.x + r.width + dx > getWidth()) dx *= -1; } private void start() { while(!isVisible()) { try { Thread.sleep(25); } catch(InterruptedException e) { break; } } Thread thread = new Thread(this); thread.setPriority(Thread.NORM_PRIORITY); thread.start(); } public static void main(String[] args) { SpinTest test = new SpinTest(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(test); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); test.start(); } }
Reply With Quote