Posts Tagged ‘2d’

Unity: Is mouse (or any coordinates) within UI element’s rect

Monday, March 30th, 2015

Here’s a quick way to check if the mouse or any other coordinates are within any UI object’s boundaries.

This method doesn’t use raycast so it ignores all overlapping objects, it works just like ActionScript’s object.HitTest(coords) function.

public bool AreCoordsWithinUiObject(Vector2 coords, GameObject gameObj)
	Vector2 localPos = gameObj.transform.InverseTransformPoint(coords);
	return ((RectTransform) gameObj.transform).rect.Contains(localPos);

// Example usage
bool isMouseOverIcon = AreCoordsWithinGameObject(Input.mousePosition, _myUiIcon);

Unity: Getting screen size in units (2D)

Wednesday, January 14th, 2015

When doing 2D games in Unity it is often handy to know where the borders of the screen are in units so one can for example spawn units on the edge of the screen or detect when something leaves it.

Fortunately it’s easy to figure out when using orthographic camera.

Camera.main.orthographicSize is always half of the total screen height, with the width changing with the aspect ratio. You can get the top or bottom coordinates by adding/subtracting it to/from the camera’s y position.

For the width you can then multiply the aspect ratio with the orthographic size,
camera.orthographicSize * Screen.width/Screen.height , to get half of the total screen width.

You can then get the x position of the screen’s left border like this:

float leftSideOfScreen = Camera.main.transform.position.x - Camera.main.orthographicSize * Screen.width / Screen.height;