/
Cinemachine3rdPersonFollow.cs
345 lines (307 loc) · 14.3 KB
/
Cinemachine3rdPersonFollow.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#if !CINEMACHINE_NO_CM2_SUPPORT
using System;
using UnityEngine;
namespace Unity.Cinemachine
{
/// <summary>
/// Third-person follower, with complex pivoting: horizontal about the origin,
/// vertical about the shoulder.
/// </summary>
[Obsolete("Cinemachine3rdPersonFollow has been deprecated. Use CinemachineThirdPersonFollow instead")]
[CameraPipeline(CinemachineCore.Stage.Body)]
[AddComponentMenu("")]
[SaveDuringPlay]
[HelpURL(Documentation.BaseURL + "manual/Cinemachine3rdPersonFollow.html")]
public class Cinemachine3rdPersonFollow : CinemachineComponentBase
, CinemachineFreeLookModifier.IModifierValueSource
, CinemachineFreeLookModifier.IModifiablePositionDamping
, CinemachineFreeLookModifier.IModifiableDistance
{
/// <summary>How responsively the camera tracks the target. Each axis (camera-local)
/// can have its own setting. Value is the approximate time it takes the camera
/// to catch up to the target's new position. Smaller values give a more rigid
/// effect, larger values give a squishier one.</summary>
[Tooltip("How responsively the camera tracks the target. Each axis (camera-local) "
+ "can have its own setting. Value is the approximate time it takes the camera "
+ "to catch up to the target's new position. Smaller values give a more "
+ "rigid effect, larger values give a squishier one")]
public Vector3 Damping;
/// <summary>Position of the shoulder pivot relative to the Follow target origin.
/// This offset is in target-local space.</summary>
[Header("Rig")]
[Tooltip("Position of the shoulder pivot relative to the Follow target origin. "
+ "This offset is in target-local space")]
public Vector3 ShoulderOffset;
/// <summary>Vertical offset of the hand in relation to the shoulder.
/// Arm length will affect the follow target's screen position
/// when the camera rotates vertically.</summary>
[Tooltip("Vertical offset of the hand in relation to the shoulder. "
+ "Arm length will affect the follow target's screen position when "
+ "the camera rotates vertically")]
public float VerticalArmLength;
/// <summary>Specifies which shoulder (left, right, or in-between) the camera is on.</summary>
[Tooltip("Specifies which shoulder (left, right, or in-between) the camera is on")]
[Range(0, 1)]
public float CameraSide;
/// <summary>How far behind the hand the camera will be placed.</summary>
[Tooltip("How far behind the hand the camera will be placed")]
public float CameraDistance;
#if CINEMACHINE_PHYSICS
/// <summary>Camera will avoid obstacles on these layers.</summary>
[Header("Obstacles")]
[Tooltip("Camera will avoid obstacles on these layers")]
public LayerMask CameraCollisionFilter;
/// <summary>
/// Obstacles with this tag will be ignored. It is a good idea
/// to set this field to the target's tag
/// </summary>
[TagField]
[Tooltip("Obstacles with this tag will be ignored. "
+ "It is a good idea to set this field to the target's tag")]
public string IgnoreTag = string.Empty;
/// <summary>
/// Specifies how close the camera can get to obstacles
/// </summary>
[Tooltip("Specifies how close the camera can get to obstacles")]
[Range(0, 1)]
public float CameraRadius;
/// <summary>
/// How gradually the camera moves to correct for occlusions.
/// Higher numbers will move the camera more gradually.
/// </summary>
[Range(0, 10)]
[Tooltip("How gradually the camera moves to correct for occlusions. " +
"Higher numbers will move the camera more gradually.")]
public float DampingIntoCollision;
/// <summary>
/// How gradually the camera returns to its normal position after having been corrected by the built-in
/// collision resolution system. Higher numbers will move the camera more gradually back to normal.
/// </summary>
[Range(0, 10)]
[Tooltip("How gradually the camera returns to its normal position after having been corrected by the built-in " +
"collision resolution system. Higher numbers will move the camera more gradually back to normal.")]
public float DampingFromCollision;
#endif
// State info
Vector3 m_PreviousFollowTargetPosition;
Vector3 m_DampingCorrection; // this is in local rig space
#if CINEMACHINE_PHYSICS
float m_CamPosCollisionCorrection;
#endif
void OnValidate()
{
CameraSide = Mathf.Clamp(CameraSide, -1.0f, 1.0f);
Damping.x = Mathf.Max(0, Damping.x);
Damping.y = Mathf.Max(0, Damping.y);
Damping.z = Mathf.Max(0, Damping.z);
#if CINEMACHINE_PHYSICS
CameraRadius = Mathf.Max(0.001f, CameraRadius);
DampingIntoCollision = Mathf.Max(0, DampingIntoCollision);
DampingFromCollision = Mathf.Max(0, DampingFromCollision);
#endif
}
void Reset()
{
ShoulderOffset = new Vector3(0.5f, -0.4f, 0.0f);
VerticalArmLength = 0.4f;
CameraSide = 1.0f;
CameraDistance = 2.0f;
Damping = new Vector3(0.1f, 0.5f, 0.3f);
#if CINEMACHINE_PHYSICS
CameraCollisionFilter = 0;
CameraRadius = 0.2f;
DampingIntoCollision = 0;
DampingFromCollision = 2f;
#endif
}
float CinemachineFreeLookModifier.IModifierValueSource.NormalizedModifierValue
{
get
{
var up = VirtualCamera.State.ReferenceUp;
var rot = FollowTargetRotation;
var a = Vector3.SignedAngle(rot * Vector3.up, up, rot * Vector3.right);
return Mathf.Clamp(a, -90, 90) / -90;
}
}
Vector3 CinemachineFreeLookModifier.IModifiablePositionDamping.PositionDamping
{
get => Damping;
set => Damping = value;
}
float CinemachineFreeLookModifier.IModifiableDistance.Distance
{
get => CameraDistance;
set => CameraDistance = value;
}
/// <summary>True if component is enabled and has a Follow target defined</summary>
public override bool IsValid => enabled && FollowTarget != null;
/// <summary>Get the Cinemachine Pipeline stage that this component implements.
/// Always returns the Aim stage</summary>
public override CinemachineCore.Stage Stage { get { return CinemachineCore.Stage.Body; } }
#if CINEMACHINE_PHYSICS
/// <summary>
/// Report maximum damping time needed for this component.
/// </summary>
/// <returns>Highest damping setting in this component</returns>
public override float GetMaxDampTime()
{
return Mathf.Max(
Mathf.Max(DampingIntoCollision, DampingFromCollision),
Mathf.Max(Damping.x, Mathf.Max(Damping.y, Damping.z)));
}
#endif
/// <summary>Orients the camera to match the Follow target's orientation</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Elapsed time since last frame, for damping calculations.
/// If negative, previous state is reset.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
if (IsValid)
{
if (!VirtualCamera.PreviousStateIsValid)
deltaTime = -1;
PositionCamera(ref curState, deltaTime);
}
}
/// <summary>This is called to notify the user that a target got warped,
/// so that we can update its internal state to make the camera
/// also warp seamlessly.</summary>
/// <param name="target">The object that was warped</param>
/// <param name="positionDelta">The amount the target's position changed</param>
public override void OnTargetObjectWarped(Transform target, Vector3 positionDelta)
{
base.OnTargetObjectWarped(target, positionDelta);
if (target == FollowTarget)
m_PreviousFollowTargetPosition += positionDelta;
}
void PositionCamera(ref CameraState curState, float deltaTime)
{
var up = curState.ReferenceUp;
var targetPos = FollowTargetPosition;
var targetRot = FollowTargetRotation;
var targetForward = targetRot * Vector3.forward;
var heading = GetHeading(targetRot, up);
if (deltaTime < 0)
{
// No damping - reset damping state info
m_DampingCorrection = Vector3.zero;
#if CINEMACHINE_PHYSICS
m_CamPosCollisionCorrection = 0;
#endif
}
else
{
// Damping correction is applied to the shoulder offset - stretching the rig
m_DampingCorrection += Quaternion.Inverse(heading) * (m_PreviousFollowTargetPosition - targetPos);
m_DampingCorrection -= VirtualCamera.DetachedFollowTargetDamp(m_DampingCorrection, Damping, deltaTime);
}
m_PreviousFollowTargetPosition = targetPos;
var root = targetPos;
GetRawRigPositions(root, targetRot, heading, out _, out Vector3 hand);
// Place the camera at the correct distance from the hand
var camPos = hand - (targetForward * (CameraDistance - m_DampingCorrection.z));
#if CINEMACHINE_PHYSICS
// Check if hand is colliding with something, if yes, then move the hand
// closer to the player. The radius is slightly enlarged, to avoid problems
// next to walls
float dummy = 0;
var collidedHand = ResolveCollisions(root, hand, -1, CameraRadius * 1.05f, ref dummy);
camPos = ResolveCollisions(
collidedHand, camPos, deltaTime, CameraRadius, ref m_CamPosCollisionCorrection);
#endif
// Set state
curState.RawPosition = camPos;
curState.RawOrientation = targetRot; // not necessary, but left in to avoid breaking scenes that depend on this
}
/// <summary>
/// Internal use only. Public for the inspector gizmo
/// </summary>
/// <param name="root">Root of the rig.</param>
/// <param name="shoulder">Shoulder of the rig.</param>
/// <param name="hand">Hand of the rig.</param>
public void GetRigPositions(out Vector3 root, out Vector3 shoulder, out Vector3 hand)
{
var up = VirtualCamera.State.ReferenceUp;
var targetRot = FollowTargetRotation;
var heading = GetHeading(targetRot, up);
root = m_PreviousFollowTargetPosition;
GetRawRigPositions(root, targetRot, heading, out shoulder, out hand);
#if CINEMACHINE_PHYSICS
float dummy = 0;
hand = ResolveCollisions(root, hand, -1, CameraRadius * 1.05f, ref dummy);
#endif
}
internal static Quaternion GetHeading(Quaternion targetRot, Vector3 up)
{
var targetForward = targetRot * Vector3.forward;
var planeForward = Vector3.Cross(up, Vector3.Cross(targetForward.ProjectOntoPlane(up), up));
if (planeForward.AlmostZero())
planeForward = Vector3.Cross(targetRot * Vector3.right, up);
return Quaternion.LookRotation(planeForward, up);
}
void GetRawRigPositions(
Vector3 root, Quaternion targetRot, Quaternion heading,
out Vector3 shoulder, out Vector3 hand)
{
var shoulderOffset = ShoulderOffset;
shoulderOffset.x = Mathf.Lerp(-shoulderOffset.x, shoulderOffset.x, CameraSide);
shoulderOffset.x += m_DampingCorrection.x;
shoulderOffset.y += m_DampingCorrection.y;
shoulder = root + heading * shoulderOffset;
hand = shoulder + targetRot * new Vector3(0, VerticalArmLength, 0);
}
#if CINEMACHINE_PHYSICS
Vector3 ResolveCollisions(
Vector3 root, Vector3 tip, float deltaTime,
float cameraRadius, ref float collisionCorrection)
{
if (CameraCollisionFilter.value == 0)
{
return tip;
}
var dir = tip - root;
var len = dir.magnitude;
dir /= len;
var result = tip;
float desiredCorrection = 0;
if (RuntimeUtility.SphereCastIgnoreTag(
new Ray(root, dir), cameraRadius, out RaycastHit hitInfo,
len, CameraCollisionFilter, IgnoreTag))
{
var desiredResult = hitInfo.point + hitInfo.normal * cameraRadius;
desiredCorrection = (desiredResult - tip).magnitude;
}
collisionCorrection += deltaTime < 0 ? desiredCorrection - collisionCorrection : Damper.Damp(
desiredCorrection - collisionCorrection,
desiredCorrection > collisionCorrection ? DampingIntoCollision : DampingFromCollision,
deltaTime);
// Apply the correction
if (collisionCorrection > Epsilon)
result -= dir * collisionCorrection;
return result;
}
#endif
// Helper to upgrade to CM3
internal void UpgradeToCm3(CinemachineThirdPersonFollow c)
{
c.Damping = Damping;
c.ShoulderOffset = ShoulderOffset;
c.VerticalArmLength = VerticalArmLength;
c.CameraDistance = CameraDistance;
c.CameraSide = CameraSide;
#if CINEMACHINE_PHYSICS
c.AvoidObstacles = new CinemachineThirdPersonFollow.ObstacleSettings
{
Enabled = true,
CollisionFilter = CameraCollisionFilter,
IgnoreTag = IgnoreTag,
CameraRadius = CameraRadius,
DampingFromCollision = DampingFromCollision,
DampingIntoCollision = DampingIntoCollision,
};
#endif
}
}
}
#endif