Pages

Compass in Unity3D


Tutorial about creating a Compass in Unity3D.

Level: Basic

Topics: GUI, Texture2D, Euler Angles

Final Result: Something like this

What you need:
Background texture of the compass like this -












Compass Bubble texture - Google for some bubble icons, I got mine from here.

To the code minions....

Class members:
//For holding the compass textures
Texture2D bg;
Texture2D bubble;

//"North" in the game
//0 for + Z Axis, 90 for + X Axis, etc
float north;

//Where the compass needs to be placed
Vector2 center;

//Size in pixels about how big the compass should be
Vector2 compassSize;
Vector2 bubbleSize;

//Where the compass bubble needs to be inside the compass
float radius;

Constructor:
//Set the placement of compass from size and center
compassRect = new Rect(
            center.x - compassSize.x / 2,
            center.y - compassSize.y / 2,
            compassSize.x,
            compassSize.y);
         
Update:
// Note -90 
float rot = (-90 + this.transform.eulerAngles.y - north)* Mathf.Deg2Rad;

// Bubble position
x = radius * Mathf.Cos(rot);
y = radius * Mathf.Sin(rot);

OnGUI:
// Draw the background
GUI.DrawTexture(compassRect, bg);

// Draw bubble
GUI.DrawTexture(new Rect(    center.x + x - bubbleSize.x / 2, // Compensate for texture
                            center.y + y - bubbleSize.y/2,   // width of bubble
                            bubbleSize.x,
                            bubbleSize.y),
                bubble);

Notes:
Make sure width and height of compass texture is same (or modify the logic to compensate for it)

How to test:
Import Character controller package
Add FPS controller to your scene
Add this compass componenet to it
Set the "north" angle and others params.... Run.. Done.

Download the complete code from here.