Reputation: 39
I created a small game:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <deque>
#include "raylib.h"
#include "raymath.h"
using namespace std;
// Constant Values
const int cell_size = 20; // Should be equal to the pixel size of images
const int cell_count = 40;
const int game_height = cell_size * cell_count, game_width = cell_size * cell_count;
const int FPS = 60;
const int font_size = 40;
const int game_offset = 100;
// Colors
map<string, Color> color = {
{"white", {255, 255, 255, 255}},
{"black", {0, 0, 0, 255} },
{"red" , {255, 0, 0, 255} },
{"green", {0, 255, 0, 255} },
{"blue" , {0, 0, 255, 255} }
};
// Classes
class Cannon {
public:
float cannon_height = cell_size * 6;
float cannon_width = cell_size * 4;
int speed = 2;
float reload_time = 2; // Seconds
vector<Vector2> position = {
{game_width / 2, game_height - cannon_height},
{game_width / 2 - cannon_width / 2, game_height},
{game_width / 2 + cannon_width / 2, game_height}
}; // Top, Bottom Left, Bottom, Right
void Update() {
Move();
}
void Draw() {
DrawTriangle(position[0], position[1], position[2], RED);
}
void Move() {
if (IsKeyDown(KEY_RIGHT) && position[2].x <= game_width - speed) {
for (int i = 0; i < position.size(); i++)
position[i].x += speed;
}
if (IsKeyDown(KEY_LEFT) && position[1].x >= speed) {
for (int i = 0; i < position.size(); i++)
position[i].x -= speed;
}
}
};
class Bomb {
public:
Vector2 position;
float radius = 10;
int speed = 200;
Bomb(Vector2 pos) {
position = pos;
}
void Update() {
Move();
}
void Draw() {
DrawCircle(position.x, position.y - radius, radius, RED);
}
void Move() {
position.y -= speed;
}
};
class Game {
public:
Cannon cannon = Cannon();
deque<Bomb> bombs;
double last_update_time = 0;
void Draw() {
cannon.Draw();
for (Bomb bomb : bombs) {
bomb.Draw();
}
}
void DisplayText() {
}
void Update() {
if (bombs.size() > 0)
cout << bombs[0].position.y << endl;
Shoot();
cannon.Update();
for (Bomb bomb : bombs)
bomb.Update();
if (bombs.size() > 0)
cout << bombs[0].position.y << endl;
}
void Shoot() {
if (IsKeyPressed(KEY_SPACE) && Time(cannon.reload_time))
bombs.push_front(Bomb(cannon.position[0]));
}
void GameOver() {
}
bool Time(double time_interval) {
double current_time = GetTime();
if (current_time - last_update_time >= time_interval) {
last_update_time = current_time;
return true;
}
return false;
}
};
int main()
{
// Create Window
InitWindow(game_width, game_height, "Ernest");
SetTargetFPS(FPS);
// Main Class
Game game = Game();
// Main Loop
while (!WindowShouldClose()) {
BeginDrawing();
// Update Elements
game.Update();
// Draw Elements
ClearBackground(color["black"]);
game.Draw();
EndDrawing();
}
// Close Window
CloseWindow();
return 0;
}
...but i ran into an issue:
The position of my projectile (bomb) should change, but it keeps getting reseted to its original value everytime.
Upvotes: 0
Views: 38