Skip to content

Instantly share code, notes, and snippets.

@fadookie
Last active December 9, 2024 12:18
Show Gist options
  • Save fadookie/256947788c364400abe1 to your computer and use it in GitHub Desktop.
Save fadookie/256947788c364400abe1 to your computer and use it in GitHub Desktop.
Screen-relative anchoring component for Unity3D. Find more Unity code at http://www.eliotlash.com/2015/01/unity3d-components-and-code-snippets/
/***
* This script will anchor a GameObject to a relative screen position.
* This script is intended to be used with ViewportHandler.cs by Marcel Căşvan, available here: http://gamedev.stackexchange.com/a/89973/50623
* It is also copied in this gist below.
*
* Note: For performance reasons it's currently assumed that the game resolution will not change after the game starts.
* You could not make this assumption by periodically calling UpdateAnchor() in the Update() function or a coroutine, but is left as an exercise to the reader.
*/
/* The MIT License (MIT)
Copyright (c) 2015, Eliot Lash
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class CameraAnchor : MonoBehaviour {
public enum AnchorType {
BottomLeft,
BottomCenter,
BottomRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
TopLeft,
TopCenter,
TopRight,
};
public AnchorType anchorType;
public Vector3 anchorOffset;
IEnumerator updateAnchorRoutine; //Coroutine handle so we don't start it if it's already running
// Use this for initialization
void Start () {
updateAnchorRoutine = UpdateAnchorAsync();
StartCoroutine(updateAnchorRoutine);
}
/// <summary>
/// Coroutine to update the anchor only once ViewportHandler.Instance is not null.
/// </summary>
IEnumerator UpdateAnchorAsync() {
uint cameraWaitCycles = 0;
while(ViewportHandler.Instance == null) {
++cameraWaitCycles;
yield return new WaitForEndOfFrame();
}
if (cameraWaitCycles > 0) {
print(string.Format("CameraAnchor found ViewportHandler instance after waiting {0} frame(s). You might want to check that ViewportHandler has an earlie execution order.", cameraWaitCycles));
}
UpdateAnchor();
updateAnchorRoutine = null;
}
void UpdateAnchor() {
switch(anchorType) {
case AnchorType.BottomLeft:
SetAnchor(ViewportHandler.Instance.BottomLeft);
break;
case AnchorType.BottomCenter:
SetAnchor(ViewportHandler.Instance.BottomCenter);
break;
case AnchorType.BottomRight:
SetAnchor(ViewportHandler.Instance.BottomRight);
break;
case AnchorType.MiddleLeft:
SetAnchor(ViewportHandler.Instance.MiddleLeft);
break;
case AnchorType.MiddleCenter:
SetAnchor(ViewportHandler.Instance.MiddleCenter);
break;
case AnchorType.MiddleRight:
SetAnchor(ViewportHandler.Instance.MiddleRight);
break;
case AnchorType.TopLeft:
SetAnchor(ViewportHandler.Instance.TopLeft);
break;
case AnchorType.TopCenter:
SetAnchor(ViewportHandler.Instance.TopCenter);
break;
case AnchorType.TopRight:
SetAnchor(ViewportHandler.Instance.TopRight);
break;
}
}
void SetAnchor(Vector3 anchor) {
Vector3 newPos = anchor + anchorOffset;
if (!transform.position.Equals(newPos)) {
transform.position = newPos;
}
}
#if UNITY_EDITOR
// Update is called once per frame
void Update () {
if (updateAnchorRoutine == null) {
updateAnchorRoutine = UpdateAnchorAsync();
StartCoroutine(updateAnchorRoutine);
}
}
#endif
}
The MIT License (MIT)
Copyright (c) 2014, Eliot Lash
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
// Attach this script on your main ortohgraphic camera:
/* The MIT License (MIT)
Copyright (c) 2014, Marcel Căşvan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
using System;
using System.Collections;
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent (typeof (Camera))]
public class ViewportHandler : MonoBehaviour
{
#region FIELDS
public Color wireColor = Color.white;
public float UnitsSize = 1; // size of your scene in unity units
public Constraint constraint = Constraint.Portrait;
public static ViewportHandler Instance;
public new Camera camera;
private float _width;
private float _height;
//*** bottom screen
private Vector3 _bl;
private Vector3 _bc;
private Vector3 _br;
//*** middle screen
private Vector3 _ml;
private Vector3 _mc;
private Vector3 _mr;
//*** top screen
private Vector3 _tl;
private Vector3 _tc;
private Vector3 _tr;
#endregion
#region PROPERTIES
public float Width {
get {
return _width;
}
}
public float Height {
get {
return _height;
}
}
// helper points:
public Vector3 BottomLeft {
get {
return _bl;
}
}
public Vector3 BottomCenter {
get {
return _bc;
}
}
public Vector3 BottomRight {
get {
return _br;
}
}
public Vector3 MiddleLeft {
get {
return _ml;
}
}
public Vector3 MiddleCenter {
get {
return _mc;
}
}
public Vector3 MiddleRight {
get {
return _mr;
}
}
public Vector3 TopLeft {
get {
return _tl;
}
}
public Vector3 TopCenter {
get {
return _tc;
}
}
public Vector3 TopRight {
get {
return _tr;
}
}
#endregion
#region METHODS
private void Awake()
{
camera = GetComponent<Camera>();
Instance = this;
ComputeResolution();
}
private void ComputeResolution()
{
float leftX, rightX, topY, bottomY;
if(constraint == Constraint.Landscape){
camera.orthographicSize = 1f / camera.aspect * UnitsSize / 2f;
}else{
camera.orthographicSize = UnitsSize / 2f;
}
_height = 2f * camera.orthographicSize;
_width = _height * camera.aspect;
float cameraX, cameraY;
cameraX = camera.transform.position.x;
cameraY = camera.transform.position.y;
leftX = cameraX - _width / 2;
rightX = cameraX + _width / 2;
topY = cameraY + _height / 2;
bottomY = cameraY - _height / 2;
//*** bottom
_bl = new Vector3(leftX, bottomY, 0);
_bc = new Vector3(cameraX, bottomY, 0);
_br = new Vector3(rightX, bottomY, 0);
//*** middle
_ml = new Vector3(leftX, cameraY, 0);
_mc = new Vector3(cameraX, cameraY, 0);
_mr = new Vector3(rightX, cameraY, 0);
//*** top
_tl = new Vector3(leftX, topY, 0);
_tc = new Vector3(cameraX, topY , 0);
_tr = new Vector3(rightX, topY, 0);
}
private void Update()
{
#if UNITY_EDITOR
ComputeResolution();
#endif
}
void OnDrawGizmos() {
Gizmos.color = wireColor;
Matrix4x4 temp = Gizmos.matrix;
Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
if (camera.orthographic) {
float spread = camera.farClipPlane - camera.nearClipPlane;
float center = (camera.farClipPlane + camera.nearClipPlane)*0.5f;
Gizmos.DrawWireCube(new Vector3(0,0,center), new Vector3(camera.orthographicSize*2*camera.aspect, camera.orthographicSize*2, spread));
} else {
Gizmos.DrawFrustum(Vector3.zero, camera.fieldOfView, camera.farClipPlane, camera.nearClipPlane, camera.aspect);
}
Gizmos.matrix = temp;
}
#endregion
public enum Constraint { Landscape, Portrait }
}
@fadookie
Copy link
Author

fadookie commented Feb 4, 2021

This is not a stand-alone script, it needs the CameraFit script from here to work as mentioned in the file header: http://gamedev.stackexchange.com/a/89973/50623

EDIT: I see that the author changed the name of the class. A lot of people have been confused by this so i'll rename it here and copy that file into this gist.

@roseeeeeee7
Copy link

Hi~ will this work even if my camera is set to perspective?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment