source: network-game/common/Projectile.cpp@ d03ec0f

Last change on this file since d03ec0f was d03ec0f, checked in by dportnoy <dmp1488@…>, 11 years ago

Add the Projectile class

  • Property mode set to 100644
File size: 2.2 KB
Line 
1#include "Projectile.h"
2
3#include <iostream>
4#include <sstream>
5#include <cstring>
6#include <cmath>
7
8using namespace std;
9
10Projectile::Projectile()
11{
12 this->id = 0;
13 this->pos.x = 0;
14 this->pos.y = 0;
15 this->target = 0;
16 this->speed = 0;
17 this->damage = 0;
18 this->timeLastUpdated = 0;
19}
20
21Projectile::Projectile(const Projectile& p)
22{
23 this->id = p.id;
24 this->pos.x = p.pos.x;
25 this->pos.y = p.pos.y;
26 this->target = p.target;
27 this->speed = p.speed;
28 this->damage = p.damage;
29 this->timeLastUpdated = p.timeLastUpdated;
30}
31
32Projectile::Projectile(int x, int y, int targetId, int damage)
33{
34 this->id = 0; // the server probably sets this by calling setId passing in the length of the current projectile list
35 this->pos.x = x;
36 this->pos.y = y;
37 this->target = targetId;
38 this->speed = 400;
39 this->damage = damage;
40 this->timeLastUpdated = 0;
41}
42
43Projectile::~Projectile()
44{
45}
46
47void Projectile::setId(int id)
48{
49 this->id = id;
50}
51
52void Projectile::serialize(char* buffer)
53{
54 memcpy(buffer, &this->id, 4);
55 memcpy(buffer+4, &this->pos.x, 4);
56 memcpy(buffer+8, &this->pos.y, 4);
57 memcpy(buffer+12, &this->target, 4);
58 memcpy(buffer+16, &this->speed, 4);
59 memcpy(buffer+20, &this->damage, 4);
60}
61
62void Projectile::deserialize(char* buffer)
63{
64 memcpy(&this->id, buffer, 4);
65 memcpy(&this->pos.x, buffer+4, 4);
66 memcpy(&this->pos.y, buffer+8, 4);
67 memcpy(&this->target, buffer+12, 4);
68 memcpy(&this->speed, buffer+16, 4);
69 memcpy(buffer+16, &this->speed, 4);
70 memcpy(buffer+20, &this->damage, 4);
71}
72
73bool Projectile::move(map<unsigned int, Player>& mapPlayers) {
74 unsigned long long curTime = getCurrentMillis();
75 Player targetP = mapPlayers[target];
76
77 if (timeLastUpdated == 0) {
78 timeLastUpdated = curTime;
79 return false;
80 }
81
82
83 float pixels = speed * (curTime-timeLastUpdated) / 1000.0;
84 double angle = atan2(targetP.pos.y-pos.y, targetP.pos.x-pos.x);
85 float dist = sqrt(pow(targetP.pos.x-pos.x, 2) + pow(targetP.pos.y-pos.y, 2));
86
87 if (dist <= pixels) {
88 pos.x = targetP.pos.x;
89 pos.y = targetP.pos.y;
90 return true;
91 }else {
92 pos.x = pos.x + cos(angle)*pixels;
93 pos.y = pos.y + sin(angle)*pixels;
94 return false;
95 }
96}
Note: See TracBrowser for help on using the repository browser.