Click here to Skip to main content
15,886,787 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here is the java code for rotation of ball around a point, the ball is supposed to rotate around a point and not move however it moves towards the left as it rotates

What I have tried:

package draw;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Rotation extends java.applet.Applet {
    
    final static int BALL_RADIUS = 45;
    
    BufferedImage ball = null;
    
    public void init()
    {
        ball = new BufferedImage(BALL_RADIUS, BALL_RADIUS, BufferedImage.TYPE_INT_RGB);
                
        Graphics ballG = ball.getGraphics();   
             
        ballG.setColor(Color.white);
                
        for(int i=-20;i<=0;i++)
        {
         ballG.drawOval(i, i, BALL_RADIUS + ((-i)*2), BALL_RADIUS + ((-i)*2));                    
        }
    }   
    
    public void paint(Graphics g)
    {
        float angle = 0;
        double speed =  0.1;
        int x = 140;
        int y = 140;
        for(int c=0;c<1600;c++)
        {
        float radius = 4;           
        x = (int) (x + Math.cos(angle) * radius);
        y = (int) (y + Math.sin(angle) * radius);
        angle += speed;        
        g.fillRect(42, 45, getBounds().width, getBounds().height);
        g.setColor(Color.white);        
        g.drawImage(ball, x, y, this);             
        delay(25);    
    }
        System.out.println("paint() done");    
}   
    
    private void delay(int millis)
    {
        try{Thread.sleep(millis);}catch(Exception ignored){}       
    }
}
Posted
Comments
Richard MacCutchan 20-Feb-17 6:37am    
It moves all over the place when I run it. Probably because the values of x and y keep changing.
four systems 20-Feb-17 7:38am    
cool, works fine now changed the co ordinates as
x = (int) (155 + Math.cos(angle) * radius);
y = (int) (45 + Math.sin(angle) * radius);
thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900