forked from microsoft/MixedRealityToolkit-Unity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAxisSlider.cs
90 lines (74 loc) · 2.35 KB
/
AxisSlider.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 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.UI.Keyboard
{
/// <summary>
/// Axis slider is a script to lock a bar across a specific axis.
/// </summary>
public class AxisSlider : MonoBehaviour
{
public enum EAxis
{
X,
Y,
Z
}
public EAxis Axis = EAxis.X;
private float currentPos;
private float slideVel;
public float slideAccel = 5.25f;
public float slideFriction = 6f;
public float deadZone = 0.55f;
public float clampDistance = 300.0f;
public float bounce = 0.5f;
[HideInInspector]
public Vector3 TargetPoint;
private float GetAxis(Vector3 v)
{
switch (Axis)
{
case EAxis.X: return v.x;
case EAxis.Y: return v.y;
case EAxis.Z: return v.z;
}
return 0;
}
private Vector3 SetAxis(Vector3 v, float f)
{
switch (Axis)
{
case EAxis.X: v.x = f; break;
case EAxis.Y: v.y = f; break;
case EAxis.Z: v.z = f; break;
}
return v;
}
/// <summary>
/// Use late update to track the input slider
/// </summary>
private void LateUpdate()
{
float targetP = GetAxis(TargetPoint);
float dt = Time.deltaTime;
float delta = targetP - currentPos;
// Accelerate left or right if outside of deadzone
if (Mathf.Abs(delta) > deadZone * deadZone)
{
slideVel += slideAccel * Mathf.Sign(delta) * dt;
}
// Apply friction
slideVel -= slideVel * slideFriction * dt;
// Apply velocity to position
currentPos += slideVel * dt;
// Clamp to sides (bounce)
if (Mathf.Abs(currentPos) >= clampDistance)
{
slideVel *= -bounce;
currentPos = clampDistance * Mathf.Sign(currentPos);
}
// Set position
transform.localPosition = SetAxis(transform.localPosition, currentPos);
}
}
}