Home > Software design >  How to rotate a triangle about it's center?
How to rotate a triangle about it's center?

Time:06-08

    document.onkeydown = function (event) {
        switch (event.keyCode) {
            case 74:
                //player presses "j"
                px = player.calculateCentreX();
                py = player.calculateCentreY();
                x1 = rotateX(player.x1,player.y1,35,px,py);
                x2 = rotateX(player.x2,player.y2,35,px,py);
                x3 = rotateX(player.x3,player.y3,35,px,py);
                y1 = rotateY(player.x1,player.y1,35,px,py);
                y2 = rotateY(player.x2,player.y2,35,px,py);
                y3 = rotateY(player.x3,player.y3,35,px,py);
                
                player.setPoints(x1,y1,x2,y2,x3,y3);
                break;
                
            default:
                break;
        }
    };
    
    function rotateX(cx,cy,angle,px,py) {
        x = Math.cos(angle)*(px-cx) - Math.sin(angle)*(py-cy)   cx
        return x
        }
        
    function rotateY(cx,cy,angle,px,py) {
        y = Math.sin(angle)*(px-cx)   Math.cos(angle)*(py-cy)   cy
        return y
        }

I am using the above to try to rotate a triangle (the player) about it's centre whenever the user presses "J". The setPoints method simply sets the triangles x1,y1,x2,y2,x3,y3 values to the updated points. Whenever the user presses J, the triangle does rotate but grows in size - can someone point out what is wrong here?

CodePudding user response:

Seems you are using wrong argument order: function is defined with center, angle, point sequence

cx,cy, angle, px,py
  ^             ^
center        point

but you call it with point, angle, center sequence

px = player.calculateCentreX();
py = player.calculateCentreY();
x1 = rotateX(player.x1,player.y1,  35,  px,py); !!!!!
                     ^                   ^           
                   point                center calculated above

As a result, former center is rotated around vertices

  • Related