I am following along Let's Make An RPG (C++/SDL2) - Tutorials on Youtube and am stuck on Let's Make an RPG (C++/SDL2) - Part 35 Continuation on Collision (https://www.youtube.com/watch?v=DLu6g2S3Ta0&list=PLHM_A02NtaaVey-4Ezh7p6bbOsv-DKA-0).
I am trying to place a transparent rectangle over all sprites to debug collision detection. I am not getting any errors so there is no one piece of code I can show you.
Can someone please shed some light on where I went wrong. I'm very new to C++ but I'm not giving up. Thank you for your time. I'm genuinely grateful.
This is the code for both the header and cpp file of the Collision Rectangle
#include "CollisionRectangle.h"
CollisionRectangle::CollisionRectangle()
{
OffsetX = 0;
OffsetY = 0;
SetRectangle(0,0,0,0);
}
CollisionRectangle::CollisionRectangle(int x, int y, int w, int h)
{
OffsetX = x;
OffsetY = y;
SetRectangle(0,0,w,h);
}
CollisionRectangle::~CollisionRectangle()
{
//dtor
}
void CollisionRectangle::SetRectangle(int x, int y, int w, int h)
{
CollisionRect.x = x + OffsetY;
CollisionRect.y = y + OffsetY;
CollisionRect.w = w;
CollisionRect.h = h;
}
//header
#pragma once
#include "stdafx.h"
class CollisionRectangle
{
public:
CollisionRectangle();
CollisionRectangle(int x, int y, int w, int h);
~CollisionRectangle(void);
void SetRectangle(int x, int y, int w, int h);
SDL_Rect GetRectangle(){ return CollisionRect; }
void setX(int x){ CollisionRect.x = x + OffsetX; }
void setY(int y){ CollisionRect.y = y + OffsetY; }
private:
int OffsetX;
int OffsetY;
SDL_Rect CollisionRect;
};
This is the code for the both the header and the cpp file of Sprites
#include "Sprite.h"
Sprite::Sprite(SDL_Renderer* passed_renderer, std::string FilePath, int x, int y, int w, int h, float *passed_CameraX, float *passed_CameraY, CollisionRectangle passed_CollisionRect)
{
CollisionRect = passed_CollisionRect;
renderer = passed_renderer;
CollisionSDL_Rect = CollisionRect.GetRectangle();
image = NULL;
image = IMG_LoadTexture(renderer, FilePath.c_str());
if (image == NULL)
{
std::cout << "Couldn't load " << FilePath.c_str() << std::endl;
}
CollisionImage = NULL;
CollisionImage = IMG_LoadTexture(renderer, "Data/DebugImages/DebugBox.png");
if (CollisionImage == NULL)
{
std::cout << "Couldn't load " << "CollisionImage" << std::endl;
}
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
SDL_QueryTexture(image,NULL,NULL, &img_width, &img_height);
crop.x = 0;
crop.y = 0;
crop.w = img_width;
crop.h = img_height;
X_pos = x;
Y_pos = y;
Origin_X = 0;
Origin_Y = 0;
CurrentFrame = 0;
Amount_Frame_X = 0;
Amount_Frame_Y = 0;
CameraX = passed_CameraX;
CameraY = passed_CameraY;
Camera.x = rect.x + *CameraX;
Camera.y = rect.y + *CameraY;
Camera.w = rect.w;
Camera.h = rect.h;
}
void Sprite::DrawSteady()
{
SDL_RenderCopy(renderer,image, &crop, &rect);
}
void Sprite::Draw()
{
Camera.x = rect.x + *CameraX;
Camera.y = rect.y + *CameraY;
CollisionRect.setX(rect.x + *CameraX);
CollisionRect.setY(rect.y + *CameraY);
SDL_RenderCopy(renderer,image, &crop, &Camera);
SDL_RenderCopy(renderer,CollisionImage, NULL, &CollisionSDL_Rect);
}
void Sprite::SetUpAnimation(int passed_Amount_X, int passed_Amount_Y)
{
Amount_Frame_X = passed_Amount_X;
Amount_Frame_Y = passed_Amount_Y;
}
void Sprite::PlayAnimation(int BeginFrame, int EndFrame, int Row, float Speed)
{
if (animationDelay+Speed < SDL_GetTicks())
{
if (EndFrame <= CurrentFrame)
CurrentFrame = BeginFrame;
else
CurrentFrame++;
crop.x = CurrentFrame * (img_width/Amount_Frame_X);
crop.y = Row * (img_height/Amount_Frame_Y);
crop.w = img_width/Amount_Frame_X;
crop.h = img_height/Amount_Frame_Y;
animationDelay = SDL_GetTicks();
}
}
Sprite::~Sprite()
{
SDL_DestroyTexture(image);
}
void Sprite::SetX(float X)
{
X_pos = X;
rect.x = int(X_pos - Origin_X);
}
void Sprite::SetY(float Y)
{
Y_pos = Y;
rect.y = int(Y_pos - Origin_Y);
}
void Sprite::SetPosition(float X, float Y)
{
X_pos = X;
Y_pos = Y;
rect.x = int(X_pos - Origin_X);
rect.y = int(Y_pos - Origin_Y);
}
float Sprite::getX()
{
return X_pos;
}
float Sprite::getY()
{
return Y_pos;
}
void Sprite::SetOrigin(float X, float Y)
{
Origin_X = X;
Origin_Y = Y;
SetPosition(getX(),getY());
}
void Sprite::SetWidth(int W)
{
rect.w = W;
}
void Sprite::SetHeight(int H)
{
rect.h = H;
}
int Sprite::GetWidth()
{
return rect.w;
}
int Sprite::GetHeight()
{
return rect.h;
}
//header
#pragma once
#include "stdafx.h"
#include "SDL_Setup.h"
#include "CollisionRectangle.h"
class Sprite
{
public:
Sprite(SDL_Renderer* passed_renderer, std::string FilePath, int x, int y, int w, int h, float *CameraX, float *CameraY, CollisionRectangle passed_CollisionRect);
~Sprite();
void Draw();
void DrawSteady();
void SetX(float X);
void SetY(float Y);
void SetPosition(float X, float Y);
float getX();
float getY();
void SetOrigin(float X, float Y);
int GetWidth();
int GetHeight();
void SetHeight(int H);
void SetWidth(int W);
void PlayAnimation(int BeginFrame, int EndFrame, int Row, float Speed);
void SetUpAnimation(int passed_Amount_X, int passed_Amount_Y);
private:
CollisionRectangle CollisionRect;
SDL_Rect Camera;
SDL_Rect CollisionSDL_Rect;
float *CameraX;
float *CameraY;
float Origin_X;
float Origin_Y;
float X_pos;
float Y_pos;
SDL_Texture* image;
SDL_Texture* CollisionImage;
SDL_Rect rect;
SDL_Rect crop;
SDL_Renderer* renderer;
int img_width;
int img_height;
int CurrentFrame;
int animationDelay;
int Amount_Frame_X;
int Amount_Frame_Y;
};
Related
I'm trying to make a color picker tool in OpenGL. It works you can use the code below. However there is one glaring issue, if you test the program you will find that if you click the black background, the color selected will become black. So my question is how do I change the code such that it recognizes which polygon I clicked or recognizes that I clicked on something or a polygon.
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
#include <iterator>
//static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mod);
static void mouse_cursor_callback(GLFWwindow* window, double xpos, double ypos);
float randfloat(){
float r = ((float)(rand() % 10))/10;
return r;
}
class RGB{
public:
float r;
float g;
float b;
void setColor(float _r, float _g, float _b){
r = _r;
g = _g;
b = _b;
}
};
RGB selected_col;
RGB mixColor(RGB color1, RGB color2){
float r = 0;
float g = 0;
float b = 0;
r = sqrt((pow(color1.r,2)+pow(color2.r,2))/2);
g = sqrt((pow(color1.g,2)+pow(color2.g,2))/2);
b = sqrt((pow(color1.b,2)+pow(color2.b,2))/2);
RGB a;
a.setColor(r,g,b);
return a;
}
int main() {
int side_count;
std::cout<<"Type the no. of sides: "<<std::endl;
std::cin>>side_count;
if(side_count < 3){
return 1;
}
srand((unsigned)time(0));
float rs[side_count];
float gs[side_count];
float bs[side_count];
RGB colors[side_count];
for (int i=0;i<side_count;i++)
{
rs[i] = randfloat();
gs[i] = randfloat();
bs[i] = randfloat();
colors[i].setColor(rs[i],gs[i],bs[i]);
}
GLFWwindow* window;
if (!glfwInit())
return 1;
window = glfwCreateWindow(400, 400, "Window", NULL, NULL);
//glfwSetMouseButtonCallback(window, mouseButtonCallback);
glfwSetCursorPosCallback(window, mouse_cursor_callback);
if (!window) {
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
if(glewInit()!=GLEW_OK)
std::cout<<"Error"<<std::endl;
RGB mcol = colors[1];
for(int i=0;i<side_count-1;i++)
{
mcol = mixColor(mcol, colors[i+1]);
}
while(!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor3f(mcol.r,mcol.g,mcol.b);glVertex2f(0,0);
//glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
for(int i=0; i<=side_count;i++)
{
float r = rs[i%side_count];
float g = gs[i%side_count];
float b = bs[i%side_count];
float x = 0.5f * sin(2.0*M_PI*i/side_count);
float y = 0.5f * cos(2.0*M_PI*i/side_count);
glColor3f(r,g,b);glVertex2f(x,y);
}
glEnd();
glBegin(GL_QUADS);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-1.0f,0.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-.5f,0.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-.5f,1.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-1.0f,1.5f);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
/*static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods){
if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS){
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
//std::cout<<"X: "<<xPos<<" Y: "<<yPos<<std::endl;
double x=xPos;
int height,width;
glfwGetWindowSize(window, &width, &height);
double y = height - yPos;
unsigned char pixel[4];
glReadPixels(x, y, 1, 1, GL_RGB,GL_UNSIGNED_BYTE, &pixel);
selected_col.setColor((float)pixel[0]/255,(float)pixel[1]/255,(float)pixel[2]/255);
//std::cout<<"R: "<<selected_col.r<<" G: "<<selected_col.g<<" B: "<<selected_col.b<<std::endl;
}
}*/
void mouse_cursor_callback( GLFWwindow * window, double xpos, double ypos)
{
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE)
{
return;
}
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
//std::cout<<"X: "<<xPos<<" Y: "<<yPos<<std::endl;
double x=xPos;
int height,width;
glfwGetWindowSize(window, &width, &height);
double y = height - yPos;
unsigned char pixel[4];
glReadPixels(x, y, 1, 1, GL_RGB,GL_UNSIGNED_BYTE, &pixel);
selected_col.setColor((float)pixel[0]/255,(float)pixel[1]/255,(float)pixel[2]/255);
//std::cout<<"R: "<<selected_col.r<<" G: "<<selected_col.g<<" B: "<<selected_col.b<<std::endl;
}
All my sprites are reversed when I try to draw my isometric map.
Here is the tileset.png mentionned in the following code :
Object.h/Object.cpp
I can use them to draw tiles, UI element, etc. ...
#pragma once
class Object {
public:
//FUNCTIONS
Object();
void addComponent(float value);
int getComponent(float index);
void editComponent(float index, float value);
void deleteComponent(float index);
private:
vector<int> components;
};
#include "Object.cpp"
-
#pragma once
//FUNCTIONS
Object::Object() {
//...
}
void Object::addComponent(float value) {
components.push_back(value);
}
int Object::getComponent(float index) {
return components[index];
}
void Object::editComponent(float index, float value) {
components[index] = value;
}
void Object::deleteComponent(float index) {
components.erase(components.begin() + index);
}
Note: I may have weird includes, I'm struggling with visual studio ha ha.
Scene.h/Scene.cpp
Handle data & graphics
#pragma once
class Scene {
public:
Scene(float w, float h, int mapx, int mapy, int tilesize, int mapwidth, int mapheight);
void run();
void addLayer();
void loadTileset(sf::String url);
void loadUiTileset(sf::String url);
//functions
//...
//getters
//...
//setters
//...
private:
sf::RenderWindow window;
float width;
float height;
int nb_layers;
int map_x;
int map_y;
int map_width;
int map_height;
int tile_size;
int selected_tile_index;
sf::RenderTexture texture;
sf::Sprite tile;
sf::Sprite map;
sf::Texture tileset;
vector<Object> tiles;
sf::Texture uiTileset;
//private functions
void updateMap();
//...
void processEvent();
void update(sf::Time deltaTime);
void render();
//...
};
#include "Scene.cpp"
-
#pragma once
//functions
Scene::Scene(float w, float h, int mapx, int mapy, int tilesize, int mapwidth, int mapheight) : window(sf::VideoMode(w, h), "Editor") {
width = w;
height = h;
map_x = mapx;
map_y = mapy;
map_width = mapwidth;
map_height = mapheight;
tile_size = tilesize;
selected_tile_index = 0;//default
nb_layers = 0;
}
void Scene::run() {
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
sf::Time TimePerFrame = sf::seconds(1.f / 60.f);
while (window.isOpen()) {
processEvent();
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame) {
timeSinceLastUpdate -= TimePerFrame;
processEvent();
update(TimePerFrame);
}
render();
}
}
void Scene::addLayer() {
nb_layers += 1;
int tile_x = map_x,
tile_y = map_y,
num_layer = nb_layers - 1,
layer_pos = (num_layer * tile_size) / 2,
tile_zOrder = -1;
tile_y -= layer_pos;
int x = map_x,
y = map_y;
for (int h = 0; h < map_height; h++) {
for (int w = 0; w < map_width; w++) {
tile_zOrder = (w * (h + 1)) + (num_layer * 10);
x = carthesianToIsometric(tile_x, tile_y)[0];
y = carthesianToIsometric(tile_x, tile_y)[1] - layer_pos;
cout << x << ", " << y << endl;
Object tile;
tile.addComponent(selected_tile_index);
tile.addComponent(x);
tile.addComponent(y);
tile.addComponent(tile_zOrder);
tile.addComponent(num_layer);
tiles.push_back(tile);
tile_x += tile_size;
}
tile_x = 0;
tile_y += tile_size;
}
updateMap();
}
void Scene::loadTileset(sf::String url) {
if (!tileset.loadFromFile(url))
{
cout << std::string(url) << "couldn't be loaded..." << endl;
}
}
void Scene::loadUiTileset(sf::String url) {
if (!uiTileset.loadFromFile(url))
{
cout << std::string(url) << "couldn't be loaded..." << endl;
}
}
//getters
//...
//setters
//...
//private functions
void Scene::updateMap() {
int tile_position_x = 0,
tile_position_y = 0;
int tile_x = 0,
tile_y = 0;
if (!texture.create(map_width * tile_size, (map_height * tile_size) / 2))
cout << "Texture couldn't be loaded... " << endl;
texture.clear(sf::Color(133, 118, 104, 255));
sf::Sprite image;
image.setTexture(tileset);
int tileset_width = image.getGlobalBounds().width,
tileset_height = image.getGlobalBounds().height;
tile.setTexture(tileset);
for (int tile_index = 0; tile_index < tiles.size(); tile_index++) {
tile_position_x = getTilePosition(tileset_width, tileset_height, tiles[tile_index].getComponent(0), tile_size)[0];
tile_position_y = getTilePosition(tileset_width, tileset_height, tiles[tile_index].getComponent(0), tile_size)[1];
tile.setTextureRect(sf::IntRect(tile_position_x, tile_position_y, tile_size, tile_size));
tile_x = tiles[tile_index].getComponent(1);
tile_y = tiles[tile_index].getComponent(2);
tile.setPosition(sf::Vector2f(tile_x, tile_y));
texture.draw(tile);
}
map.setTexture(texture.getTexture());
}
void Scene::processEvent() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Escape)
window.close();
break;
}
}
}
void Scene::update(sf::Time deltaTime) {
//REMEMBER: distance = speed * time
//MOVEMENT, ANIMATIONS ETC. ..
}
void Scene::render() {
window.clear();
window.draw(map);
window.display();
}
main.cpp
#pragma once
//global functions + main headers + class headers =>
#include "globalfunctions.h"
int main() {
int map_width = 15,
map_height = 15,
tile_size = 64;
float scene_width = map_width * tile_size,
scene_height = (map_height * tile_size) / 2;
Scene engine(scene_width, scene_height, 0, 0, tile_size, map_width, map_height);
engine.loadTileset("tileset.png");
//engine.loadUiTileset("menu.png");
engine.addLayer();
//...
engine.run();
return EXIT_SUCCESS;
}
globalfunctions.h
Some utility functions.
getTilePosition(...) allow me to get x, y on a texture with a given tile index. Example : if I want to draw the tile n°0 of the tileset texture.
#pragma once
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<float> getTilePosition(float tileset_width, float tileset_height, float tile_index, float tile_size) {//In a tileset
float tileX = 0,
tileY = 0,
tilePerLine = 0;
tilePerLine = tileset_width / tile_size;
tileY = floor(tile_index / tilePerLine);
tileX = ((tile_index + 1) - (tileY * tilePerLine)) - 1;
tileX *= tile_size;
tileY *= tile_size;
vector<float> coords;
coords.push_back(tileX);
coords.push_back(tileY);
return coords;
}
vector<int> carthesianToIsometric(int x, int y) {
vector<int> coords;
float isoX = (x - y) / 2,
isoY = (x + y) / 4;
coords.push_back(isoX);
coords.push_back(isoY);
return coords;
}
#include "Object.h"
#include "Scene.h"
//...
And here, the WTF result I get :
Thanks for reading all that weird code !
Edit :
When I change
tile.setPosition(sf::Vector2f(tile_x, tile_y));
to
tile.setPosition(sf::Vector2f(0, 0));
in updateMap() from scene.cpp :
Unfortunatly, I cannot explain why. Maybe it will help you to understand the problem.
In case someone encounter the same problem :
As #Spectre suggested it was a problem of the sfml function draw().
http://en.sfml-dev.org/forums/index.php?topic=6903.0
You need to use display on the sf::renderTexture after your cleared it.
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 6 years ago.
I created base Sprite class:
#ifndef SPRITE_H_
#define SPRITE_H_
#include<iostream>
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
class Sprite
{
public:
Sprite(SDL_Texture* texture, int x, int y, int w, int h, SDL_Renderer* p_renderer);
virtual ~Sprite();
SDL_Rect getRect();
SDL_Texture* loadImage(std::string file_path);
void drawSprite();
void setPosition(int x, int y);
float getXpos();
float getYpos();
private:
SDL_Renderer* gRenderer;
SDL_Texture* image;
SDL_Rect rect;
//for position update
float x_pos;
float y_pos;
};
#endif /* SPRITE_H_ */
#include "Sprite.h"
Sprite::Sprite(SDL_Texture* texture, int x, int y, int w, int h, SDL_Renderer* p_renderer)
{
gRenderer = p_renderer;
image = texture;
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
x_pos = x;
y_pos = y;
}
Sprite::~Sprite()
{
SDL_DestroyTexture(image);
}
float Sprite::getXpos()
{
return x_pos;
}
float Sprite::getYpos()
{
return y_pos;
}
SDL_Texture* loadImage(std::string file_path, SDL_Renderer* p_renderer)
{
return IMG_LoadTexture(p_renderer, file_path.c_str());
}
void Sprite::drawSprite()
{
SDL_RenderCopy(gRenderer, image, NULL, &rect);
}
Next I created Bird class that is using Sprite class as a base:
/*
* Bird.h
*
* Created on: 1 maj 2016
* Author: Astral
*/
#ifndef BIRD_H_
#define BIRD_H_
#include "Sprite.h"
class Bird: public Sprite
{
public:
Bird(SDL_Texture* texture, int x, int y, int w, int h, SDL_Renderer* p_renderer, float p_speed, float p_acceleration);
virtual ~Bird();
void updateBird(int x, int y);
void handleInput();
private:
float speed, acceleration;
};
#endif /* BIRD_H_ */
#include "Bird.h"
Bird::Bird(SDL_Texture* texture, int x, int y, int w, int h, SDL_Renderer* p_renderer, float p_speed, float p_acceleration):Sprite(texture, x, y, w, h, p_renderer)
{
speed = p_speed;
acceleration = p_acceleration;
}
Bird::~Bird()
{
}
void Bird::updateBird(int x, int y)
{
Sprite::setPosition(x, y);
}
Now I'm getting error and I have no idea why:
../src/Bird.cpp:18: undefined reference to `Sprite::setPosition(int, int)'
Sprite.cpp
1.
void Sprite::setPosition(int x, int y)
{
x_pos = x;
y_pos = y;
}
2.
SDL_Texture* loadImage(std::string file_path, SDL_Renderer* p_renderer)
↓
SDL_Texture* Sprite::loadImage(std::string file_path)
I have been working in a zombie arcade game, I am experimenting an strange problem. I created a class called GameObject and a class called Human that inherits from GameOBject, then I declared two more called; Zombie and Player. The problem is that when I create two or more characters (instances) of this four classes the game stops working, I detected that in the classes Zombie and Player the problem only occurs when I call the method update (only these classes use it). This method is supposed to control the activities of each character.
The graphics and animated sprites are managed separately from the character, they (the characters) only call some methods to control the sprite update, those orders are processed when updating the screen.
I just want you to tell me what is happening, I think the problem is in the update method of the classes Zombie and Player.
The project is divided in different files.
I don't think this matters but I am using CodeBlocks and tdm-gcc.
main.cpp:
#include "game_classes.h"
bool working = true, redraw = true;
int main(){
init_game_classes();
Player player(200, 200);
std::vector<Zombie *> zombie_list;
for(unsigned int i = 0; i < 2; i++){
Zombie *zombie = new Zombie(i * 100, 12, &player);
zombie_list.push_back(zombie);
}
while(working){
input();
if(event.type == ALLEGRO_EVENT_TIMER){//main loop
player.update();
for(unsigned int i = 0; i < zombie_list.size(); i++){
zombie_list[i]->update();
}
redraw = true;
}
else if(event.type == ALLEGRO_EVENT_DISPLAY_CLOSE){
working = false;
}
if(redraw and al_is_event_queue_empty(event_queue)){//updating display
update_animated_models();
blit_models();
update_display();
redraw = false;
}
}
for(unsigned int i = 0; i < zombie_list.size(); i++)
delete zombie_list[i];
quit();
return 0;
}
render.h:
#include <vector>
#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
int global_ticks_per_frame = 0;
ALLEGRO_BITMAP *map_background = NULL;
class Model;
std::vector<Model *> model_list;
class Model{
protected:
int x = 0, y = 0, width, height;
int source_x = 0, source_y = 0, source_width, source_height;
public:
ALLEGRO_BITMAP *sheet = NULL;
bool hide = false;
int flags = 0;
Model(const char *path, int width, int height){
this->sheet = al_load_bitmap(path);
al_convert_mask_to_alpha(this->sheet, al_map_rgb(255, 0, 255));
this->source_width = al_get_bitmap_width(this->sheet);
this->source_height = al_get_bitmap_height(this->sheet);
this->width = width;
this->height = height;
model_list.insert(model_list.begin(), this);
}
Model(ALLEGRO_BITMAP *image, int width, int height){
this->sheet = image;
al_convert_mask_to_alpha(this->sheet, al_map_rgb(255, 0, 255));
this->source_width = al_get_bitmap_width(this->sheet);
this->source_height = al_get_bitmap_height(this->sheet);
this->width = width;
this->height = height;
model_list.insert(model_list.begin(), this);
}
~Model(){
al_destroy_bitmap(this->sheet);
model_list.erase(model_list.begin() + this->index());
}
void show(){
if(not this->hide){
al_draw_scaled_bitmap(this->sheet, this->source_x, this->source_y, this->source_width, this->source_height, x, y, width, height, this->flags);
}
}
void set_x(int x){
this->x = x;
}
unsigned int index(){
for(unsigned int i = 0; i < model_list.size(); i++){
if(model_list[i] == this)
return i;
}
}
bool set_y(int y){
this->y = y;
model_list.erase(model_list.begin() + this->index());
int this_relative_y = this->y + this->height;
unsigned int i = 0;
while(i < model_list.size()){
int from_list_relative_y = model_list[i]->y + model_list[i]->height;
if(this_relative_y < from_list_relative_y){
model_list.insert(model_list.begin() + i, this);
return false;
}
i += 1;
}
model_list.push_back(this);
return false;
}
int get_y(){
return this->y;
}
int get_x(){
return this->x;
}
unsigned int get_width(){
return this->width;
}
unsigned int get_height(){
return this->height;
}
};
void blit_models(){
for(unsigned int i = 0; i < model_list.size(); i++)
model_list[i]->show();
}
class AnimatedModel;
std::vector<AnimatedModel *> animated_model_list;
class AnimatedModel : public Model{
private:
unsigned int ticks_per_frame, ticks_counter = 0;
unsigned int current_frame = 0, frame_count;
public:
bool stop = false;
void set_speed(unsigned int new_speed){
this->ticks_per_frame = new_speed;
}
AnimatedModel(const char *path, unsigned int frames, unsigned int ticks_per_frame, int width, int height) : Model(path, width, height){
this->ticks_per_frame = ticks_per_frame;
this->frame_count = frames;
this->source_width /= frames;
animated_model_list.push_back(this);
}
AnimatedModel(ALLEGRO_BITMAP *image, unsigned int frames, unsigned int ticks_per_frame, int width, int height) : Model(image, width, height){
this->ticks_per_frame = ticks_per_frame;
this->frame_count = frames;
this->source_width /= frames;
animated_model_list.push_back(this);
}
~AnimatedModel(){
for(unsigned int i = 0; i < animated_model_list.size(); i++){
if(animated_model_list[i] == this){
animated_model_list.erase(animated_model_list.begin() + i);
}
}
}
void fix_sheet_looking(){
if(not this->stop)
this->source_x = this->current_frame*this->source_width;
}
void play(){
if(this->ticks_counter >= this->ticks_per_frame + global_ticks_per_frame){
this->current_frame += 1;
if(this->current_frame >= this->frame_count)
this->current_frame = 0;
this->ticks_counter = 0;
}
else{
this->ticks_counter += 1;
}
}
void update(){
if(not this->stop){
this->play();
this->fix_sheet_looking();
}
}
void set_frame(unsigned int i){
this->current_frame = i;
}
unsigned int get_frame(){
return this->current_frame;
}
};
void update_animated_models(){
for(unsigned int i = 0; i < animated_model_list.size(); i++)
animated_model_list[i]->update();
}
game_classes.h:
#include "render.h"
#include "touch.h"
#include "window_control.h"
#include <string>
#include <iostream>
ALLEGRO_BITMAP *zombie_sprite = NULL;
ALLEGRO_BITMAP *human_sprite = NULL;
void init_game_classes(){
init_window_control();
zombie_sprite = al_load_bitmap("textures/zombie/sprite.png");
human_sprite = al_load_bitmap("textures/human/sprite.png");
}
int control_key_up = ALLEGRO_KEY_UP, control_key_down = ALLEGRO_KEY_DOWN, control_key_right = ALLEGRO_KEY_RIGHT, control_key_left = ALLEGRO_KEY_LEFT;
int control_key_run = ALLEGRO_KEY_Z;
HitBoxList character_body_reg;
HitBoxList item_body_reg;
class GameObjec{
protected:
unsigned int walking_speed;
HitBoxList *last_coll_test = NULL;
int last_x, last_y;
int body_high;
int left_distance;
public:
HitBox *body = NULL;
AnimatedModel *sprite = NULL;
void set_x(int x){
this->sprite->set_x(x);
this->last_x = this->body->x;
this->body->x = x + this->left_distance;
}
void set_y(int y){
this->sprite->set_y(y);
this->last_y = this->body->y;
this->body->y = y + this->body_high;
}
int get_x(){
return this->sprite->get_x();
}
int get_y(){
return this->sprite->get_y();
}
void slide_x(short int direction){
character_body_reg.pop(this->body);
this->last_coll_test = this->body->slide_x(this->walking_speed*direction, &character_body_reg);
character_body_reg.push(this->body);
this->set_x(this->body->x - this->left_distance);
}
void slide_y(short int direction){
character_body_reg.pop(this->body);
this->last_coll_test = this->body->slide_y(this->walking_speed*direction, &character_body_reg);
character_body_reg.push(this->body);
this->set_y(this->body->y - this->body_high);
}
void show_hitbox(){
al_draw_rectangle(this->body->x, this->body->y, this->body->x + this->body->width, this->body->y + this->body->height, al_map_rgb(255, 0, 0), 1);
}
GameObjec(int x, int y, unsigned int walking_speed, const char *sprite_image_path, int frames, int ticks_per_frame, int sprite_width, int sprite_height, int body_high, int body_len){
this->walking_speed = walking_speed;
this->body_high = body_high;
this->sprite = new AnimatedModel(sprite_image_path, frames, ticks_per_frame, sprite_width, sprite_height);
this->left_distance = (this->sprite->get_width() - body_len)/2;
this->body = new HitBox;
this->sprite->set_x(x);
this->sprite->set_y(y);
this->body->width = body_len;
this->body->height = this->sprite->get_height() - this->body_high;
this->body->x = x + left_distance;
this->body->y = y + this->body_high;
this->last_x = this->body->x;
this->last_y = this->body->y;
character_body_reg.push(this->body);
}
~GameObjec(){
delete this->sprite;
character_body_reg.pop(this->body);
delete this->body;
}
void draw_hitbox(){
al_draw_rectangle(this->body->x, this->body->y, this->body->x + this->body->width, this->body->y + this->body->height, al_map_rgb(255, 0, 0), 0);
}
};
class Human : public GameObjec{
protected:
bool walking = false;
public:
Human(int x, int y, const char *sprite_image_path) : GameObjec(x, y, 2, sprite_image_path, 2, 7, 64, 80, 60, 32){}
~Human(){}
void walk_down(){
this->slide_y(1);
this->sprite->stop = false;
this->walking = true;
}
void walk_up(){
this->slide_y(-1);
this->sprite->stop = false;
this->walking = true;
}
void walk_right(){
this->slide_x(1);
this->sprite->stop = false;
this->sprite->flags = 0;
this->walking = true;
}
void walk_left(){
this->slide_x(-1);
this->sprite->stop = false;
this->sprite->flags = ALLEGRO_FLIP_HORIZONTAL;
this->walking = true;
}
};
class Player : public Human{
public:
Player(int x, int y) : Human(x, y, "textures/human/sprite.png"){
}
void control(){
if(get_key(control_key_down))
this->walk_down();
else if(get_key(control_key_up))
this->walk_up();
if(get_key(control_key_right))
this->walk_right();
else if(get_key(control_key_left))
this->walk_left();
if(not this->walking){
this->sprite->set_frame(0);
this->sprite->fix_sheet_looking();
this->sprite->stop = true;
}
if(this->last_x == this->body->x and this->last_y == this->body->y)
this->walking = false;
}
void update(){
this->control();
}
};
class Zombie : public Human{
private:
//Player *to_kill;
int to_kill_x, to_kill_y;
unsigned int walk_ticks_counter = 0, follow_ticks_counter = 0;
public:
Player *to_kill;
void fix_to_kill_position(){
if(this->to_kill){
this->to_kill_x = this->to_kill->body->x;
this->to_kill_y = this->to_kill->body->y;
}
else{
this->to_kill_x = this->body->x;
this->to_kill_y = this->body->y;
}
}
Zombie(int x, int y, Player *to_kill) : Human(x, y, "textures/zombie/sprite.png"){
this->sprite->set_speed(23);
this->walking_speed = 1;
this->to_kill = to_kill;
this->fix_to_kill_position();
}
void control(){
if(this->body->y < to_kill_y)
this->walk_down();
else if(this->body->y > to_kill_y)
this->walk_up();
if(this->body->x < to_kill_x)
this->walk_right();
else if(this->body->x > to_kill_x)
this->walk_left();
if(not this->walking){
this->sprite->set_frame(0);
this->sprite->fix_sheet_looking();
this->sprite->stop = true;
}
}
void update(){
if(this->follow_ticks_counter == 78){
this->fix_to_kill_position();
this->follow_ticks_counter = 0;
}
else{
this->follow_ticks_counter += 1;
}
if(this->walk_ticks_counter == 2){
this->control();
this->walk_ticks_counter = 0;
}
else{
this->walk_ticks_counter += 1;
}
if(this->last_x == this->body->x and this->last_y == this->body->y)
this->walking = false;
}
};
Hi I made a level generator with a 3D Buzz tutorial called Evil Monkeys.
I generated a level but I can't get it to draw on the screen.
My code:
Level.cpp
#include "Level.h"
#include <stdlib.h>
#include "Sprite.h"
Level::Level(drawEngine *de, int w, int h)
{
drawArea = de;
width = w;
height = h;
gamer = 0;
//create memory for our level
level = new char *[width];
for(int x = 0; x < width; x++)
{
level[x] = new char[height];
}
//create the level
createLevel();
drawArea->setMap(level);
}
Level::~Level()
{
for(x = 0; x < width; x++)
delete []level[x];
delete [] level;
}
void Level::createLevel(void)
{
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
int random = rand() % 100;
if (y == 0 || y == height - 1 || x == 0 || x == width - 1)
{
level[x][y] = TILE_WALL;
}
else
{
if (random < 90 || (x < 3 && y < 3))
level[x][y] = TILE_EMPTY;
else
level[x][y] = TILE_WALL;
}
}
}
}
void Level::draw(void)
{
// level to be drawn here
drawArea->drawBackground();
}
Level.h
#ifndef LEVEL_H
#define LEVEL_H
enum
{
TILE_EMPTY,
TILE_WALL
};
#include "drawEngine.h"
class Character;
class Level
{
public:
Level(drawEngine *de, int width = 30, int height = 20);
~Level();
int x;
int y;
void addPlayer(Character *p);
void update(void);
void draw(void);
bool keyPress(char c);
protected:
void createLevel(void);
private:
int width;
int height;
char **level;
Character *gamer;
drawEngine *drawArea;
};
#endif
Game.cpp
#include "Game.h"
#include <conio.h>
#include <iostream>
#include "drawEngine.h"
#include "Character.h"
#include <windows.h>
using namespace std;
//this will give ME 32 fps
#define GAME_SPEED 25.33
bool Runner::run()
{
level = new Level(&drawArea, 30, 20);
drawArea.createBackgroundTile(TILE_EMPTY, ' ');
drawArea.createBackgroundTile(TILE_WALL, '+');
drawArea.createSprite(0, '$');
gamer = new Character(&drawArea, 0);
level->draw();
char key = ' ';
startTime = timeGetTime();
frameCount = 0;
lastTime = 0;
posX = 0;
while (key != 'q')
{
while(!getInput(&key))
{
timerUpdate();
}
//gamer->keyPress(key);
//cout << "Here's what you pressed: " << key << endl;
}
delete gamer;
cout << frameCount / ((timeGetTime() - startTime) / 100) << " fps " << endl;
cout << "Game Over" << endl;
return true;
}
bool Runner::getInput(char *c)
{
if (kbhit())
{
*c = getch();
return true;
}
}
void Runner::timerUpdate()
{
double currentTime = timeGetTime() - lastTime;
if (currentTime < GAME_SPEED)
return;
frameCount++;
lastTime = timeGetTime();
}
game.h
#ifndef GAME_H
#define GAME_H
#include "drawEngine.h"
#include "Sprite.h"
#include "Character.h"
#include "level.h"
class Runner
{
public:
bool run();
Runner(){};
protected:
bool getInput(char *c);
void timerUpdate();
private:
Level *level;
Character* gamer;
double frameCount;
double startTime;
double lastTime;
int posX;
drawEngine drawArea;
};
#endif
drawEngine.cpp
#include <iostream>
#include "drawEngine.h"
#include <windows.h>
using namespace std;
drawEngine::drawEngine(int index, int xSize, int ySize, int x, int y)
{
screenWidth = x;
screenHeight = y;
map = 0;
//set cursor visibility to false
//cursorVisibility(false);
}
drawEngine::~drawEngine()
{
cursorVisibility(true);
//set cursor visibility to true
}
int drawEngine::createSprite(int index, char c)
{
if (index >= 0 && index < 16)
{
spriteImage[index] = c;
return index;
}
return -1;
}
void drawEngine::deleteSprite(int index)
{
// in this implemantation we don't need it
}
void drawEngine::drawSprite(int index, int posX, int posY)
{
//go to the correct location
gotoxy (index, posX, posY);
// draw the sprite
cout << spriteImage[index];
cursorVisibility(false);
}
void drawEngine::eraseSprite(int index, int posX, int posY)
{
gotoxy (index, posX, posY);
cout << ' ';
}
void drawEngine::setMap(char **data)
{
map = data;
}
void drawEngine::createBackgroundTile(int index, char c)
{
if (index >= 0 && index < 16)
{
tileImage[index] = c;
}
}
void drawEngine::drawBackground(void)
{
if(map)
{
for(int y = 0; y < screenHeight; y++)
{
gotoxy(0,y, 0);
for(int x = 0; x < screenWidth; x++)
cout << tileImage[map[x][y]];
}
}
}
void drawEngine::gotoxy(int index, int x, int y)
{
HANDLE output_handle;
COORD pos;
pos.X = x;
pos.Y = y;
output_handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output_handle, pos);
}
void drawEngine::cursorVisibility(bool visibility)
{
HANDLE output_handle;
CONSOLE_CURSOR_INFO cciInfo;
cciInfo.dwSize = 1;
cciInfo.bVisible = visibility;
output_handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorInfo(output_handle, &cciInfo);
}
drawEngine.h
#ifndef DRAWENGINE_H
#define DRAWENGINE_H
class drawEngine
{
public:
drawEngine(int index, int xSize = 30, int ySize = 20, int x = 0, int y = 0);
~drawEngine();
drawEngine(){};
int createSprite(int index, char c);
void deleteSprite(int index);
void eraseSprite(int index, int posX, int posY);
void createBackgroundTile(int index, char c);
void drawSprite(int index, int posX, int posY);
void drawBackground(void);
void setMap(char **);
protected:
char **map;
int screenWidth, screenHeight;
char spriteImage[16];
char tileImage[16];
private:
void gotoxy(int index, int x, int y);
void cursorVisibility(bool visibility);
};
#endif
I've also got Sprite.cpp, Sprite.h, Character.h,Character.cpp and main.cpp if you need them
Ok, I made it through the code and found one issue. The Runner class encapsulates a drawEngine object. At the constructor of Runner, the default c'tor of drawEngine is called, which doesn't set values for sceenWidth and screenHeight (or any other member). Luckily in debug mode, they are defaulted to 0xcccccccc which is negative so you're drawBackground returns immediately (Visual Studio 2010).
You should change that c'tor (or even remove it) and corretly initialize the engine in runner's constructor, e.g.:
class Runner {
public:
Runner() : drawArea(0, width, height, ?, ?){};
[...]
};
Further, the x and y members are used in the loops in drawBackground. You should use screenWidth and screenWidth, resp. BTW, I don't know what x and y should be in drawEngine
UPDATE: The x and y coordinates at the gotoxy call in drawBackground are mixed up, so you draw everything on the same line. BTW: what is index used for?