This repository was archived by the owner on Jun 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhysicsModel.cpp
More file actions
55 lines (41 loc) · 1.9 KB
/
PhysicsModel.cpp
File metadata and controls
55 lines (41 loc) · 1.9 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
#include "PhysicsModel.h"
PhysicsModel::PhysicsModel(Transform* newTransform, PhysicsBodyConfig bodyConfig) {
_transform = newTransform;
_bodyStats = bodyConfig;
_velocity = Vector3();
_acceleration = Vector3();
_collider = nullptr;
}
PhysicsModel::~PhysicsModel() {
_transform = nullptr; //don't destroy the transform, it's not ours.
if (_collider) delete(_collider);
}
void PhysicsModel::Update(float deltaTime) {
if (_bodyStats.kinematic) return;
if (_bodyStats.mass == 0) return;
//collect any other variables needed for now.
Vector3 position = _transform->GetPosition();
//gather net forces.
if (_bodyStats.simulateGravity) _netForce += _bodyStats.gravity * _bodyStats.mass;
_netForce += Vector3(QuickDrag1D(_velocity.x), QuickDrag1D(_velocity.y), QuickDrag1D(_velocity.z));
//change acceleration based on it.
//don't increment acceleration like we do velocity, as that's not how physics works.
//theoretically this will set it to 0 if the net force is zero.
_acceleration = _netForce * _bodyStats.massInverse;
_netForce = Vector3(0, 0, 0); //make the result into a constant acceleration by resetting it here
//apply the velocity and move the object
_velocity += _acceleration * deltaTime;
position += _velocity * deltaTime;
_transform->SetPosition(position);
//now update the collider so it can update any cache it has
if (_collider) _collider->Update();
}
inline float PhysicsModel::QuickDrag1D(float velocity) {
//utilize existing cache to quickly calculate the drag.
//we aren't expecting the model to change between now and then
//so unless the object gets setters called we can assume it is the same as last frame
//across coefficients, volume and mass.
//return a negative if incoming is positive, otherwise return a positive.
if (velocity < 0.0f) return ((velocity * velocity) * 0.5f) * _bodyStats.dragMultiplier;
return ((velocity * -velocity) * 0.5f) * _bodyStats.dragMultiplier;
}