Rotating Shapes in a Coordinate Plane Using Javascript

Categories: VCS

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:

SquareBlock: Object
  color: "green"
  coords: Array[4]
    0: Object
      x: 0
      y: 1
    1: Object
      x: 1
      y: 1
    2: Object
      x: 0
      y: 0
    3: Object
      x: 1
      y: 0
  pivot: 2

This is my function to rotate said block:

function rotateBlock(){
  var blockCoords = Tetris.Model.getCurrentBlock().coords;
  var pivotIndex = Tetris.Model.getCurrentBlock().pivot;
  var pivot = blockCoords[pivotIndex];
  // So we need to rotate the points relative to the pivot point
  //  at this moment in time. The equation for a 90 deg. rotation 
  //  is (x,y) -> (y,-x).
  for(var i=0;i<blockCoords.length;i++){
    var relativeX = blockCoords[i].x - pivot.x;
    var relativeY = blockCoords[i].y - pivot.y;
    var rotatedX = relativeY;
    var rotatedY = -relativeX;
    blockCoords[i].x = pivot.x + rotatedX;
    blockCoords[i].y = pivot.y + rotatedY;
  }
}

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)

«
»