-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntity.cpp
More file actions
82 lines (71 loc) · 2.37 KB
/
Entity.cpp
File metadata and controls
82 lines (71 loc) · 2.37 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
#include <SFML/Graphics.hpp>
#include <cmath>
#include "Entity.h"
Entity::Entity() : Entity(0, sf::Vector2(0.f, 0.f), sf::Color::Cyan, 0, sf::Vector2(0.f, 0.f), false) {}
Entity::Entity(int r, sf::Vector2f position, sf::Color color, float speed,
sf::Vector2f destination, bool isPlayer)
: speed(speed), destination(destination), isPlayer(isPlayer), isDestroyed(false)
{
body = new sf::CircleShape();
body->setRadius(r);
body->setPosition(position);
body->setFillColor(color);
// Might not be needed
body->setOrigin(r / 2, r / 2);
}
Entity::Entity(const Entity &entity)
: speed(entity.speed), destination(entity.destination), isPlayer(entity.isPlayer), isDestroyed(entity.isDestroyed)
{
body = new sf::CircleShape(*entity.body);
}
void Entity::move()
{
// Creates a vector movement in the direction of destination
sf::Vector2f movement = destination - body->getPosition();
// Finds the length of the vector
float length = std::sqrt(movement.x * movement.x + movement.y * movement.y);
// Divide by length to normalise the length of the vector to 1
if (length != 0)
movement /= length;
// Multiply by speed
movement *= speed;
// Moves the entity only if it is further away from its destination then half the speed. This value can be tweaked
if (length > speed / 2)
{
body->move(movement);
}
}
bool Entity::checkCollision(Entity *entity)
{
// Check if the entity is not null and if it is not the same player type
if (entity != nullptr && (entity->isPlayer != this->isPlayer))
{
// Calculate the distance between the two entities
sf::Vector2f relativePosition = body->getPosition() - entity->body->getPosition();
float distance = std::sqrt((relativePosition.x * relativePosition.x) + (relativePosition.y * relativePosition.y));
// Return true if the distance is less than the sum of their radii
return (distance < body->getRadius() + entity->body->getRadius());
}
else
{
return false;
}
}
void Entity::draw(sf::RenderWindow *win)
{
win->draw(*body);
}
sf::Vector2f Entity::getPosition()
{
return body->getPosition();
}
sf::Vector2f Entity::getDestination()
{
return destination;
}
float Entity::getSpeed()
{
return speed;
}
bool Entity::getIsDestroyed() { return isDestroyed; }
Entity::~Entity() { delete body; }