Converting Between Coordinate Systems

From Unify Community Wiki
Jump to: navigation, search

One thing you'll find yourself doing almost constantly in Unity is converting between a number of different coordinate systems. E.g. if you want to display text over someone's head you need to convert their world position into screen coordinates. If you want to figure out where a user just clicked you may need to convert screen coordinates into world coordinates. If you want one object to fly towards another object you need to convert the second object's world position into the first object's local coordinate system.

Converting from World Position to a Transform's Local Position

Example: object A wants to know where object B is in relation to it (e.g. left, right, straight ahead).

Inside a script attached to A, we would write:

var relativePosition = transform.InverseTransformPoint( B.position ); 
if( relativePosition.x < 0 ){
  // B is to the LEFT of A

Converting from World Position to Screen Coordinates

Example: We want to draw a health bar above an entity using the GUI class.

Inside a script attached to the entity we would write:

var healthBarWidth : int;
var healthBarHeight : int;
var healthBarTexture : Texture2D;
var screenPosition : Vector3;
function Update (){
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
screenPosition.y = Screen.height - screenPosition.y; // the GUI coordinate system is upside down relative to every other coordinate system
function OnGUI (){
GUI.DrawTexture(Rect(screenPosition.x - healthBarWidth/2, screenPosition.y - healthBarHeight/2, healthBarWidth, healthBarHeight), healthBarTexture);

Note: Camera.main is *usually* the camera you'll want to use. If not, you'll want a reference to the appropriate camera.

... to be continued ...

Personal tools