forked from microsoft/MixedRealityToolkit-Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FixedAngularSize.cs
73 lines (66 loc) · 2.85 KB
/
FixedAngularSize.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// Causes a Hologram to maintain a fixed angular size, which is to say it
/// occupies the same pixels in the view regardless of its distance from
/// the camera.
/// </summary>
public class FixedAngularSize : MonoBehaviour
{
[Tooltip("Off sets the scale ratio so that text does not scale down too much. (Set to zero for linear scaling)")]
public float SizeRatio = 0;
// The ratio between the transform's local scale and its starting
// distance from the camera.
private float startingDistance;
private Vector3 startingScale;
private void Start()
{
// Calculate the XYZ ratios for the transform's localScale over its
// initial distance from the camera.
startingDistance = Vector3.Distance(CameraCache.Main.transform.position, transform.position);
startingScale = transform.localScale;
SetSizeRatio(SizeRatio);
}
/// <summary>
/// Manually update the OverrideSizeRatio during runtime or through UnityEvents in the editor
/// </summary>
/// <param name="ratio"> 0 - 1 : Use 0 for linear scaling</param>
public void SetSizeRatio(float ratio)
{
if (ratio == 0)
{
if (startingDistance > 0.0f)
{
// set to a linear scale ratio
SizeRatio = 1 / startingDistance;
}
else
{
// If the transform and the camera are both in the same
// position (that is, the distance between them is zero),
// disable this Behaviour so we don't get a DivideByZero
// error later on.
enabled = false;
#if UNITY_EDITOR
Debug.LogWarning("The object and the camera are in the same position at Start(). The attached FixedAngularSize Behaviour is now disabled.");
#endif // UNITY_EDITOR
}
}
else
{
SizeRatio = ratio;
}
}
private void Update()
{
float distanceToHologram = Vector3.Distance(CameraCache.Main.transform.position, transform.position);
// create an offset ratio based on the starting position. This value creates a new angle that pivots
// on the starting position that is more or less drastic than the normal scale ratio.
float curvedRatio = 1 - startingDistance * SizeRatio;
transform.localScale = startingScale * (distanceToHologram * SizeRatio + curvedRatio);
}
}
}