Question

I want to move this small rectangle about the circumference of the circle, so that I looks and moves like a canon.

enter image description here

Code

private void doDrawing(Graphics g){
    g.setColor(Color.BLUE);
    g.fillArc(-CANON_RADIUS/2, this.getHeight()-CANON_RADIUS/2, CANON_RADIUS, CANON_RADIUS, 0, 90);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.BLUE);
    Rectangle rect = new Rectangle(CANON_RADIUS/2, this.getHeight()-CANON_RADIUS/2, CANON_WIDTH, CANON_HEIGHT);
    AffineTransform transform = new AffineTransform();
    transform.rotate(Math.toRadians(-60), rect.getX() + rect.width/2, rect.getY() + rect.height/2);
    Shape transformed = transform.createTransformedShape(rect);
    g2d.fill(transformed);
}

This code rotates rectangle about its centre. How can I rotate rectangle around the circumference?

Was it helpful?

Solution

First things first, you can use a transformation matrix for this, like you are already using: http://en.wikipedia.org/wiki/Transformation_matrix

Edit: looking at your code, you want to rotate your canon around an anchor. Please look at the javadocs: http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html

public void rotate(double theta, double anchorx, double anchory)

the first argument is your rotation, the last two arguments have to be the middle of your cannon base! like screen.height and 0 for your example:

AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(-60), 0, Screen.height);
Shape transformed = transform.createTransformedShape(rect);
g2d.fill(transformed);

second approach could be move the middle of your rotated rectangle around the radius of your base.

like (pseudocode):

Point p = circle.getPoint();
shape.moveto(p.x-(shape.width/2),p.y-(shape.height/2));
g2d.fill(shape);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top