Select Page

## VXR Trackday game

Here is the game I had that rotation problem with. Use the mouse to control the steering. Post your best times in the comments!

## Code snippets highlight

I just installed this great plug-in for highlighting code in my posts:

Snippet Highlight

Install and put <pre></pre> tags around the code you want to use.

## Rotation problem

I was building a nice little car racing game last week and got stuck on a problem to do with rotation. Getting the car to follow the cursor wasn’t a problem but as I put a restriction on the amount the car could turn, I couldn’t just make the angles equal each other. This meant that I had to calculate the difference between the angles and then rotate in the right direction a maximum amount each frame. Everything is going well until we go past 9 o’clock and suddenly rotation jumps from 180 to -180. Now my math difference calculations are out the window and my car is spinning back the wrong way! This is the solution:

```if (Math.abs (difference) > 180) { difference = difference > 0 ? difference - 360 : 360 + difference; }```

And in context:
(150 and 125 represent the centre point of the 300×250 MPU)
``` public function setAngle():Void{ var angle:Number = Math.round(Math.atan2((_ymouse-150),(_xmouse-125)) *180/Math.PI);   var difference:Number = Math.round(angle - car._rotation); if (Math.abs (difference) > 180) {   difference = difference > 0 ? difference - 360 : 360 + difference;   }   if(difference > 5){   car._rotation += 6 * speed/16;   } else if (difference < -5){   car._rotation -= 6 * speed/16;   } else {   //do nothing   } }```
looks like I have to work out how to post code in this WYSIWYG editor…