forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCameraSmoothTrack.cs
More file actions
90 lines (77 loc) · 2.88 KB
/
Copy pathCameraSmoothTrack.cs
File metadata and controls
90 lines (77 loc) · 2.88 KB
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
using Unity.Physics;
using Unity.Physics.Extensions;
using Unity.Physics.Systems;
using Unity.Entities;
using UnityEngine;
using RaycastHit = Unity.Physics.RaycastHit;
// Camera Utility to smoothly track a specified target from a specified location
// Camera location and target are interpolated each frame to remove overly sharp transitions
public class CameraSmoothTrack : MonoBehaviour
{
public GameObject Target;
public GameObject LookTo;
[Range(0,1)] public float LookToInterpolateFactor = 0.9f;
public GameObject LookFrom;
[Range(0, 1)] public float LookFromInterpolateFactor = 0.9f;
private Vector3 oldPositionTo;
// Start is called before the first frame update
void Start()
{
if (LookTo == null)
{
oldPositionTo = (gameObject.transform.position + Vector3.forward);
}
else
{
oldPositionTo = LookTo.transform.position;
}
}
// Update is called once per frame
void LateUpdate()
{
if (!enabled) return;
Vector3 newPositionFrom = (LookFrom == null) ? gameObject.transform.position : LookFrom.transform.position;
Vector3 newPositionTo = Vector3.forward;
if (LookTo == null)
{
newPositionTo = gameObject.transform.rotation * newPositionTo;
}
else
{
newPositionTo = LookTo.transform.position;
}
PhysicsWorld world = World.Active.GetExistingSystem<BuildPhysicsWorld>().PhysicsWorld;
// check barrier
{
var rayInput = new RaycastInput
{
Ray = {Origin = newPositionFrom, Direction = newPositionTo - newPositionFrom},
Filter = CollisionFilter.Default
};
if (world.CastRay(rayInput, out RaycastHit rayResult))
{
newPositionFrom = rayResult.Position;
}
}
if (Target != null)
{
// add velocity
var em = World.Active.EntityManager;
var e = Target.GetComponent<GameObjectEntity>();
if ((em != null) && (e != null) && (e.Entity != Entity.Null))
{
Vector3 lv = world.GetLinearVelocity(world.GetRigidBodyIndex(e.Entity));
lv *= Time.fixedDeltaTime;
newPositionFrom += lv;
newPositionTo += lv;
}
}
newPositionFrom = Vector3.Lerp(gameObject.transform.position, newPositionFrom, LookFromInterpolateFactor);
newPositionTo = Vector3.Lerp(oldPositionTo, newPositionTo, LookToInterpolateFactor);
Vector3 newForward = newPositionTo - newPositionFrom;
newForward.Normalize();
Quaternion newRotation = Quaternion.LookRotation(newForward, Vector3.up);
gameObject.transform.SetPositionAndRotation(newPositionFrom, newRotation);
oldPositionTo = newPositionTo;
}
}