简体   繁体   中英

How to rotate a triangle about it's center?

    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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM