Rotating Shapes in a Coordinate Plane Using Javascript

tetris logoFor this week’s Viking Code School project we’re tasked with building a Javascript/jQuery version of Tetris. One of the more complicated aspects of this project was building pieces that actually rotate when a button is pressed (like Tetris pieces are wont to do).

Here’s my implementation for the rotation. Keep in mind that Tetris.Model.getCurrentBlock() returns the CurrentBlock object from my model. This object consists of Coordinates in the form of  {x: x, y: y} among some other useful things like the color of the block and the coordinate that I’d like to use as the Pivot  point, which will come in handy later.

This is what a CurrentBlock object might look like:

This is my function to rotate said block:

There are a lot of variables for now for the sake of clarity, but let’s take a look at what’s actually going on. First of all, I’m getting the coordinates for each SubBlock  in my CurrentBlock  (saved as blockCoords ) so that I can cycle through them. Then, I’m getting the index of my Pivot  coordinate for this shape and then getting the actual coordinates of said Pivot .

After that, my for  loop cycles through each SubBlock in my CurrentBlock  and converts it to a point relative to the Pivot  point. In Euclidian geometry I am essentially treating the Pivot  point as the origin and then making the other points relative to this origin. Then I use the equation for a 90 degree rotation around the origin (which my points are now relative to) and then convert these points back to the area on the coordinate plane where they originally were by adding the x and y elements of the rotated point to the x and y elements of the pivot point. This will yield us the proper coordinates for each of the other SubBlocks  relative to the Pivot  point.

What do you think of this technique? Are there any better ways to rotate a block using Javascript in a coordinate plane? Looking forward to hearing your answers too!

For the latest version of my Tetris game click here (NOTE: it’s not fully functional yet)