1

I'm trying to do a rotate method. First I click in any vertice of a shape and then every time the mouse moves, the shape should rotate according to the angle between that vertice, and the new point.

It should rotate around in own center (the centroid), but it ends up deforming the shape, and making it smaller and smaller. I dont know why isnt this working, the target is the point where the mouse is right now, and the index is the index of the vertice that was clicked to initiate the rotation.

The Vector points contains all the vertices of the shape.

Here is a video of what happens.

edit 1: Now the getAngle funcion returns a value in radians.

New video: https://www.youtube.com/watch?v=y0Ch6gE5Ebs

public void rotate(Point target, int index) {
        double centerx = getCentroid().getX();
        double centery = getCentroid().getY();
        float angle = getAngle(target, points.get(index));
        Vector<Point> pointsAux = new Vector<Point>(points.size());
        for(int i = 0; i<points.size(); i++){
            Point p = points.get(i);
        double newx = centerx + (p.getX()-centerx)*Math.cos(angle) - (p.getY()-centery)*Math.sin(angle);
        double newy = centery + (p.getX()-centerx)*Math.sin(angle) - (p.getY()-centery)*Math.cos(angle);
        p = new Point((int)newx, (int)newy);
        pointsAux.add(p);
        }
        points.clear();
        points.addAll(pointsAux);
    }   

    public float getAngle(Point target, Point clicked) {
        return (float) Math.atan2(target.getX()- clicked.getX(), target.getY() - clicked.getY());
    }
public Point getCentroid(){
        int sumx = 0;
        int sumy = 0;
        for(int i = 0; i<points.size();i++){
            sumx+=points.get(i).getX();
            sumy+=points.get(i).getY();
        }
         Point centroid = new Point(sumx/points.size(), sumy/points.size());
         return centroid;
    }

I would be grattefull for any kind of help.

Miguel Morujão
  • 1,131
  • 1
  • 14
  • 39

0 Answers0