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.
Subscribe to:
Post Comments (Atom)
Works good Thanks....
ReplyDeleteI tried implementing this as a component to my player's character, and the pip didn't move at all. I tried doing it as a component of my MainCamera, and the pip still didn't move. What's wrong here?
ReplyDeleteHow to get free Unity 3D Camera System download and set up video step-by-step.
ReplyDeleteRead the description for the download link and instruction :D
http://www.youtube.com/watch?v=bDB_Fhhx0R8&feature=plcp
Thank you, it works great, I just used your
ReplyDeletebg texture and a 16x16 bubble
radius 32
center x 64 y 64
compass size 128 by 128
bubble size 16 by 16
https://sites.google.com/site/terrymorgan1213
Hi. this is good. Do you share to complate project?
ReplyDelete