Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading