-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfish.cpp
More file actions
67 lines (58 loc) · 2.15 KB
/
fish.cpp
File metadata and controls
67 lines (58 loc) · 2.15 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
#include "fish.h"
#include <algorithm>
#include <raymath.h>
#define ACCEL 200.0f
#define FRICTION 10.0f
#define MAX_SPEED 700.0f
#define RESET_SPEED 250.0f
Fish::Fish(const float width_limit, const float height_limit) {
position = { static_cast<float>(GetRandomValue(20.0f, width_limit - 20.0f)), static_cast<float>(GetRandomValue(20.0f, height_limit - 20.0f))};
velocity = { 0, 0 };
acceleration = { 0, 0};
rotation = 0.0f;
this->width_limit = width_limit;
this->height_limit = height_limit;
}
void Fish::Update(const float deltaTime) {
GatherInstructions(); // Fish-specific behaviour
ApplyPhysics(deltaTime); // Universal swimming physics
}
void Fish::ApplyPhysics(const float deltaTime) {
// Applies acceleration based on input and friction
if (acceleration.x != 0) {
velocity.x += acceleration.x * ACCEL * deltaTime;
} else {
velocity.x -= velocity.x * FRICTION * deltaTime;
}
if (acceleration.y != 0) {
velocity.y += acceleration.y * ACCEL * deltaTime;
} else {
velocity.y -= velocity.y * FRICTION * deltaTime;
}
// Limits max speed and staggers movement to simulate fish-ness
if (Vector2Length(velocity) > MAX_SPEED) {
velocity = Vector2Scale(Vector2Normalize(velocity), RESET_SPEED);
}
// Applies changes to current position
position.x += velocity.x * deltaTime;
position.y += velocity.y * deltaTime;
// Check for collision
if (position.x < 0 || position.x > width_limit) {
position.x = std::clamp(position.x, 0.0f, width_limit);
velocity.x = 0;
}
if (position.y < 0 || position.y > height_limit) {
position.y = std::clamp(position.y, 0.0f, height_limit);
velocity.y = 0;
}
// Updates sprite rotation
if (Vector2Length(velocity) > 0.0001f) {
rotation = atan2f(-velocity.y, -velocity.x) * (180.0f / PI);
}
}
void Fish::Respawn(float width_limit, float height_limit) {
position = { static_cast<float>(GetRandomValue(20.0f, width_limit - 20.0f)), static_cast<float>(GetRandomValue(20.0f, height_limit - 20.0f))},
velocity = { 0, 0 },
acceleration = { 0, 0};
rotation = 0.0f;
}