Controlling a character with the mouse in Silverlight
Here’s a problem I had recently with a Silverlight game I’m developing. It’s a top-down 2D game, and I want the character to be controlled by the mouse, and I want it to be rotated to face the direction the mouse is moving.
Moving the character it easy. Just create a MouseMove event handler and set the position of the character object.
Rotating the character is a little trickier. The obvious solution is to just take the vector between the new position and the previous position, and use atan to get the angle.
The problem here is that dx and dy are usually very small, especially when the mouse is accelerating, which causes the character to end up facing in only a few directions. And there’s no smooth turning motion. If the mouse moves by (1, 0) one frame and (0, 1) the next, the character suddenly changes from facing straight right to straight down.
Another solution is to change the angle by only a certain amount each frame.
But I don’t like that. It just looks ugly, with all the ifs, and having to handle wrapping around from 360 to 0. Plus it’s still not very smooth when the mouse moves slowly.
My final solution was to create an “anchor” point behind the character, and use that to determine the rotation. The new angle will be based on the vector to the mouse position from the anchor point, instead of from the character position.

With a few tweaks to AnchorDistance, this worked perfectly. In the screenshot you can see the history as the blue polygon turned while it moved from left to right (with a ghost of the character added every 5 frames). The anchor is the green square at the back of the character.
You can get the Silverlight 3 project for Visual Studio 2008 here.