Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Created October 24, 2014 02:42
Show Gist options
  • Save grimmdev/4b3bee5d0b44ac198e34 to your computer and use it in GitHub Desktop.
Save grimmdev/4b3bee5d0b44ac198e34 to your computer and use it in GitHub Desktop.
Useful for getting world cordinates of screen limits in both ortho and perspective camera types.
using UnityEngine;
using System.Collections;
public class ScreenManager : MonoBehaviour
{
// mouse position in screen cordinates.
public Vector3 screenPosition;
// mouse position in world space.
public Vector3 worldPosition;
// Bounds of the screen in world space.
public Vector2 screenBounds;
// Use this for initialization
void Awake ()
{
if(Camera.main.isOrthoGraphic)
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width,Screen.height));
}else{
screenBounds = GetWorldPositionOnPlane(new Vector3(Screen.width,Screen.height,0));
}
}
// Update is called once per frame
void Update ()
{
// Mouse input in screen cordinates
screenPosition.x = Input.mousePosition.x;
screenPosition.z = 0f;
screenPosition.y = (Screen.height - Input.mousePosition.y);
// Mouse input in world cordinates based on camera perspective
if(Camera.main.isOrthoGraphic)
{
worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
worldPosition.z = 0f;
}else{
worldPosition = GetWorldPositionOnPlane(Input.mousePosition);
}
}
// Gets world cordinates from screen cordinates
public Vector3 GetWorldPositionOnPlane(Vector3 screenPosition) {
Ray ray = Camera.main.ScreenPointToRay(screenPosition);
Plane xy = new Plane(Vector3.forward, new Vector3(0, 0, 0));
float distance;
xy.Raycast(ray, out distance);
return ray.GetPoint(distance);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment