summary refs log tree commit diff stats
path: root/src/components/physics_body.cpp
blob: 72f2fd88434e80743733e1ea11f8e9db0da4e8cf (plain) (blame)
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
#include "physics_body.h"
#include "game.h"

void PhysicsBodyComponent::receive(Game&, Entity&, const Message& msg)
{
  if (msg.type == Message::Type::walkLeft)
  {
    velocity.first = -90;
  } else if (msg.type == Message::Type::walkRight)
  {
    velocity.first = 90;
  } else if (msg.type == Message::Type::stopWalking)
  {
    velocity.first = 0.0;
  } else if (msg.type == Message::Type::stopMovingHorizontally)
  {
    velocity.first = 0.0;
  } else if (msg.type == Message::Type::stopMovingVertically)
  {
    velocity.second = 0.0;
  }
}

void PhysicsBodyComponent::tick(Game&, Entity& entity, double dt)
{
  // Accelerate
  velocity.first += accel.first * dt;
  velocity.second += accel.second * dt;
  
  // Terminal velocity
#define TERMINAL_VELOCITY_X (2 * TILE_WIDTH * FRAMES_PER_SECOND)
#define TERMINAL_VELOCITY_Y (2 * TILE_HEIGHT * FRAMES_PER_SECOND)
  if (velocity.first < -TERMINAL_VELOCITY_X) velocity.first = -TERMINAL_VELOCITY_X;
  if (velocity.first > TERMINAL_VELOCITY_X) velocity.first = TERMINAL_VELOCITY_X;
  if (velocity.second < -TERMINAL_VELOCITY_Y) velocity.second = -TERMINAL_VELOCITY_Y;
  if (velocity.second > TERMINAL_VELOCITY_Y) velocity.second = TERMINAL_VELOCITY_Y;
  
  // Do the movement
  entity.position.first += velocity.first * dt;
  entity.position.second += velocity.second * dt;
}

void PhysicsBodyComponent::detectCollision(Game& game, Entity& entity, Entity& collider, std::pair<double, double> old_position)
{
  // If already colliding, do nothing!
  if ((old_position.first + collider.size.first > entity.position.first)
    && (old_position.first < entity.position.first + entity.size.first)
    && (old_position.second + collider.size.second > entity.position.second)
    && (old_position.second < entity.position.second + entity.size.second))
  {
    return;
  }
  
  // If newly colliding, SHOCK AND HORROR!
  if ((collider.position.first + collider.size.first > entity.position.first)
    && (collider.position.first < entity.position.first + entity.size.first)
    && (collider.position.second + collider.size.second > entity.position.second)
    && (collider.position.second < entity.position.second + entity.size.second))
  {
    Message msg(Message::Type::collision);
    msg.collisionEntity = &collider;
    
    entity.send(game, msg);
  }
}