The Joystick 2.1 module from GHI Electronics is a fun and easy to use joystick controller. Joystick controllers feel like they’re going the way of the dinosaur because of touch screens. However, they’re excellent for teaching velocity based movement across a screen within a boudary. This is basis for all games.
The code can be found on my Gadgeteer GitHub repository. You can find out more about the module on the Gadgeteer Page.
Using the Joystick Module to move an ellipse around the screen.
First you need to get the basic screen dimensions
displayHeight = display_T35.Height;
displayWidth = display_T35.Width;
Get the current joystick center position. Note: There is some noise when asking the joystick for it’s position. The X/Y values vary about +/-0.02.
joystickPosition = joystick.GetJoystickPosition();
Start the joystick thread to listen for postion changes
joystickThread = new Thread(JoystickReadThread);
joystickThread.Start();
My joystick thread simply loops and calls a MoveCursor function
public void JoystickReadThread()
{
while (true)
{
MoveCursor();
Thread.Sleep(100);
}
}
The move cursor does all the fun stuff. First, determine the new position. If it’s has not moved beyond the 0.03 noise limit, return.
Joystick.Position newJoystickPosition = joystick.GetJoystickPosition();
double newX = joystickPosition.X-.5+currentPosition.X - currentPosition.X;
double newY = joystickPosition.Y-.5+currentPosition.Y - currentPosition.Y;
// did we actually move...
if (System.Math.Abs(newX) >= 0.03){realX = newX;}
if (System.Math.Abs(newY) >= 0.03){realY = newY;}
if (realX == 0.0 && realY == 0.0) return;
Did we go off the screen? If yes, then show up on the other side.
if (realX + currentPosition.X >= displayWidth) currentPosition.X = 0;
if (realX + currentPosition.X <= 0) currentPosition.X = displayWidth;
if (realY + currentPosition.Y >= displayHeight) currentPosition.Y = 0;
if (realY + currentPosition.Y <= 0) currentPosition.Y = displayHeight;
Set the current position and draw an ellipse there… finally!
currentPosition.X += realX*5;
currentPosition.Y += realY*5;
display_T35.SimpleGraphics.DisplayEllipse(Color.White, (uint)currentPosition.X, (uint)currentPosition.Y, 2, 2);