How to make cv::setMouseCallback function work - c++

I've seen a few questions that are probably the same. I am still unable to make my code work after reading the answers. So I am sorry in advance if I am repeating the posts.
I managed to write this code :
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
bool leftButtonDown = false, leftButtonUp = false;
cv::Mat img;
cv::Point cor1, cor2;
cv::Rect rect;
void mouseCall(int event, int x, int y, int, void*) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; cor1.x = x; cor1.y = y; std::cout << "Corner 1: " << cor1 << std::endl;
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - cor1.x)>20 && abs(y - cor1.y)>5) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; cor2.x = x; cor2.y = y; std::cout << "Corner 2: " << cor2 << std::endl;
}
else { std::cout << "Select more than 5 pixels" << std::endl; }
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is clicked and let off
{ //draw a rectangle continuously
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = img.clone();
rectangle(temp_img, cor1, pt, cv::Scalar(0, 0, 255));
cv::imshow("Original", temp_img);
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
cv::Mat cutTempImg(img, rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main(){
img = cv::imread("image.jpg");
cv::namedWindow("Original");
cv::imshow("Original", img);
cv::setMouseCallback("Original", mouseCall); //setting the mouse callback for selecting the region with mouse
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}
And it is working fine. Now I want to make same code, with using class.(OOP)
But cv::setMouseCallback function is not letting me do that.
Can any one help me fix this?
My second code :
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
class ResizeImage {
cv::Mat img;
cv::Point cor1, cor2;
cv::Rect rect;
std::string name;
public:
void setImg(cv::Mat img) { this->img = img; };
cv::Mat getImg() { return img; };
void setRect();
int getCoordinates1X() { return cor1.x; };
int getCoordinates1Y() { return cor1.y; };
int getCoordinates2X() { return cor2.x; };
int getCoordinates2Y() { return cor2.y; };
void setCoordinates1(int x, int y) { this->cor1.x = x; this->cor1.y = y; };
void setCoordinates2(int x, int y) { this->cor2.x = x; this->cor2.y = y; };
void mouseCall(int event, int x, int y, int flags, void* param);
void showImgOriginal();
void setImgName(std::string name) { this->name = name; };
std::string getImgName() { return name; };
};
void ResizeImage :: showImgOriginal() {
cv::namedWindow(name, CV_WINDOW_AUTOSIZE);
cv::imshow(name, img);
};
void ResizeImage::setRect() {
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
}
void ResizeImage::mouseCall(int event, int x, int y, int flags, void* param) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; setCoordinates1(x,y); std::cout << "Corner 1: " << getCoordinates1X()<<" "<<getCoordinates1Y() << std::endl;
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - cor1.x)>20 && abs(y - cor1.y)>5) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; setCoordinates2(x, y); std::cout << "Corner 2: " << getCoordinates2X() << " " << getCoordinates2Y() << std::endl;
}
else { std::cout << "Select more than 5 pixels" << std::endl; }
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is down
{
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = img.clone();
rectangle(temp_img, cor1, pt, cv::Scalar(0, 0, 255)); //drawing a rectangle continuously
cv::imshow("Original", temp_img);
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
setRect();
cv::Mat cutTempImg(img, rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main(){
cv::Mat img = cv::imread("image.jpg");
ResizeImage img_;
img_.setImg(img);
img_.setImgName("original");
img_.showImgOriginal();
cv::setMouseCallback(img_.getImgName(),img_.mouseCall());
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}
Code after changes :
//Program is loading image, and showing it to user.
//User can use mouse to make a rectangle and cut the loaded image.
//Command line is tracking mouse movements and the coordinates of the rectangle.
//User can end the program using 'q'.
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
bool leftButtonDown = false, leftButtonUp = false; //flags for mouse clicks
class ResizeImage {
cv::Mat img; //image to process
cv::Point cor1, cor2; //coordinates of selected rectangle
cv::Rect rect; //rectangle
std::string name; //windows name
public:
//////////////////////////////////////////////////////////////////////////////
ResizeImage() { std::cout << "Starting..."<<std::endl; }; //Constructor/Destructor
~ResizeImage() { std::cout << "Ending..." << std::endl; };
//////////////////////////////////////////////////////////////////////////////
void setImg(cv::Mat img) { this->img = img; };
void setImgName(std::string name) { this->name = name; }; //set functions
void setRect();
void setCoordinates1(int x, int y) { this->cor1.x = x; this->cor1.y = y; };
void setCoordinates2(int x, int y) { this->cor2.x = x; this->cor2.y = y; };
//////////////////////////////////////////////////////////////////////////////
int getCoordinates1X() { return cor1.x; }; //getfunctions
int getCoordinates1Y() { return cor1.y; };
int getCoordinates2X() { return cor2.x; };
int getCoordinates2Y() { return cor2.y; };
cv::Mat getImg() { return img; };
std::string getImgName() { return name; };
//////////////////////////////////////////////////////////////////////////////
static void mouseCall(int event, int x, int y, int flags, void* param); //static function
//////////////////////////////////////////////////////////////////////////////
void showImgOriginal(); //show function (priting image)
//////////////////////////////////////////////////////////////////////////////
};
void ResizeImage :: showImgOriginal() { //showing image
cv::namedWindow(name, CV_WINDOW_AUTOSIZE);
cv::imshow(name, img);
};
void ResizeImage::setRect() { //calculating selected rectangle
rect.width = abs(cor1.x - cor2.x);
rect.height = abs(cor1.y - cor2.y);
rect.x = cv::min(cor1.x, cor2.x);
rect.y = cv::min(cor1.y, cor2.y);
}
void ResizeImage::mouseCall(int event, int x, int y, int flags, void* param) {
if (event == cv::EVENT_LBUTTONDOWN) //finding first corner
{
leftButtonDown = true; ((ResizeImage*)param)->cor1.x = x; ((ResizeImage*)param)->cor1.y = y; //saving coordinates
std::cout << "Corner 1: " << ((ResizeImage*)param)->cor1.x << " " << ((ResizeImage*)param)->cor1.y << std::endl; //printing coordinates
}
if (event == cv::EVENT_LBUTTONUP) {
if (abs(x - ((ResizeImage*)param)->cor1.x)>20 && abs(y - ((ResizeImage*)param)->cor1.y)>10) //finding second corner and checking whether the region is too small
{
leftButtonUp = true; ((ResizeImage*)param)->cor2.x = x; ((ResizeImage*)param)->cor2.y = y; //saving coordinates
std::cout << "Corner 2: " << ((ResizeImage*)param)->cor2.x << " " << ((ResizeImage*)param)->cor2.y << std::endl; //printing coordinates
}
else { std::cout << "Select more than 10 pixels" << std::endl; } //warning if region is too small
}
if (leftButtonDown == true && leftButtonUp == false) //when the left button is down
{
cv::Point pt; pt.x = x; pt.y = y;
cv::Mat temp_img = ((ResizeImage*)param)->img.clone();
rectangle(temp_img, ((ResizeImage*)param)->cor1, pt, cv::Scalar(0, 0, 255)); //drawing a rectangle continuously
}
else if (event == cv::EVENT_MOUSEMOVE) //tracking mouse movement
{
std::cout << "Mouse moving over the window - position (" << x << ", " << y << ")" << std::endl;
}
if (leftButtonDown == true && leftButtonUp == true) //when the selection is done
{
((ResizeImage*)param)->setRect();
cv::Mat cutTempImg(((ResizeImage*)param)->img, ((ResizeImage*)param)->rect); //Selecting a ROI(region of interest) from the original img
cv::namedWindow("Cut Temporary Image");
cv::imshow("Cut Temporary Image", cutTempImg); //showing the cropped image
leftButtonDown = false;
leftButtonUp = false;
}
}
int main() {
cv::Mat img = cv::imread("image.jpg");
ResizeImage img_;
img_.setImg(img);
img_.setImgName("Original");
img_.showImgOriginal();
cv::setMouseCallback(img_.getImgName(),ResizeImage::mouseCall,&img_);
while (char(cv::waitKey(1) != 'q')) //waiting for the 'q' key to finish the execution
{
}
return 0;
}

If you want to use a class method as a callback, you should indeed declare the method as static. However, you also need to pass an object to the callback to be able to access non static members of your class such as cor1 or cor2.
Here is a minimal example of how you can achieve this:
class Call {
public:
Call(int i) : a(i){};
int a;
static void mouse(int event, int x, int y, int flags, void* param) {
std::cout << ((Call*)param)->a << std::endl;
}
};
cv::namedWindow("Call");
Call call(10);
cv::setMouseCallback("Call", Call::mouse, &call);
cv::imshow("Call", cv::Mat(100, 100, CV_8U, cv::Scalar(0)));
cv::waitKey();
I create a Call object and use its mouse method as the window callback while still passing the object to the call back.

You should make the function static:
static void mouseCall(int event, int x, int y, int flags, void* param);
and then:
cv::setMouseCallback(img_.getImgName(),ResizeImage::mouseCall);

Related

SDL2 Texture wont move when main loop event calls w, a, s, or d in c++

so i've been working on a game system/engine, for my 2D Platformer, and when i press the w, a, s, or d keys it won't move when called in the main loop event.
Here is all of my project files and everything that i've written:
main.cpp:
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <vector>
#include "RenderWindow.hpp"
#include "Entity.hpp"
#include "Utils.hpp"
int main(int argc, char const *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO) > 0)
std::cout << "ERROR: SDL_Init() HAS FAILED: SDL_ERROR => " << SDL_GetError() << std::endl;
if (!(IMG_Init(IMG_INIT_PNG)))
std::cout << "ERROR: IMG_Init() HAS FAILED: SDL_ERROR => " << SDL_GetError() << std::endl;
RenderWindow window("GAME v1.0", 1280, 720);
SDL_Texture* grassTexture = window.loadTexture("res/gfx/ground_grass.png");
SDL_Texture* playerTexture = window.loadTexture("res/gfx/ghost.png");
std::vector<Entity> platforms = {Entity(Vector2f(0, 30), grassTexture),
Entity(Vector2f(30, 30), grassTexture),
Entity(Vector2f(30, 30), grassTexture),
Entity(Vector2f(60, 30), grassTexture)};
Entity player(Vector2f(30, 8), playerTexture);
bool gameRunning = true;
SDL_Event event;
const float timeStep = 0.01f;
float accumulator = 0.0f;
float currentTime = utils::hireTimeInSeconds();
while(gameRunning)
{
int startTicks = SDL_GetTicks();
float newTime = utils::hireTimeInSeconds();
float frameTime = newTime - currentTime;
currentTime = newTime;
accumulator += frameTime;
while(accumulator >= timeStep)
{
// Get out controls and events
while(SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
gameRunning = false;
break;
// window.freeTexture(grassTexture);
// window.freeTexture(playerTexture);
}
// Add code to move the player texture
const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);
Vector2f& playerPos = player.getPos();
if(currentKeyStates[SDL_SCANCODE_W]) {
playerPos.y -= 1;
break;
}
if(currentKeyStates[SDL_SCANCODE_S]) {
playerPos.y += 1;
break;
}
if(currentKeyStates[SDL_SCANCODE_A]) {
playerPos.x -= 1;
break;
}
if(currentKeyStates[SDL_SCANCODE_D]) {
playerPos.x += 1;
break;
}
}
window.clear();
for (Entity& e : platforms)
{
window.render(e);
window.render(player);
}
window.display();
// // Add code to move the player texture
// const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL);
// Vector2f& playerPos = player.getPos();
// if(currentKeyStates[SDL_SCANCODE_W]) {
// playerPos.y -= 1;
// }
// if(currentKeyStates[SDL_SCANCODE_S]) {
// playerPos.y += 1;
// }
// if(currentKeyStates[SDL_SCANCODE_A]) {
// playerPos.x -= 1;
// }
// if(currentKeyStates[SDL_SCANCODE_D]) {
// playerPos.x += 1;
// }
//playerPos.print();
accumulator -= timeStep;
// std::cout << accumulator << std::endl;
}
// const float alpha = accumulator / timeStep; // 50%?
// window.freeTexture(grassTexture);
// window.freeTexture(playerTexture);
int frameTicks = SDL_GetTicks() - startTicks;
if (frameTicks < 1000 / window.getRefreshRate())
SDL_Delay(100 / window.getRefreshRate() - frameTicks);
}
window.cleanUp();
SDL_Quit();
return 0;
}
renderwindow.hpp:
#pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Entity.hpp"
class RenderWindow
{
public:
RenderWindow(const char* p_title, int p_w, int p_h);
SDL_Texture* loadTexture(const char* p_filePath);
int getRefreshRate();
void cleanUp();
void clear();
void render(Entity& p_entity);
//void freeTexture(SDL_Texture* p_tex);
void display();
private:
SDL_Window* window;
SDL_Renderer* renderer;
};
renderwindow.cpp:
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include "RenderWindow.hpp"
#include "Entity.hpp"
RenderWindow::RenderWindow(const char* p_title, int p_w, int p_h)
:window(NULL), renderer(NULL)
{
window = SDL_CreateWindow(p_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, p_w, p_h, SDL_WINDOW_SHOWN);
if (window == NULL)
{
std::cout << "ERROR: Window has failed to init! SDL_Error: " << SDL_GetError() << std::endl;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}
SDL_Texture* RenderWindow::loadTexture(const char* p_filePath)
{
SDL_Texture* texture = NULL;
texture = IMG_LoadTexture(renderer, p_filePath);
if (texture == NULL)
std::cout << "ERROR: Failed to load texture! SDL_Error: " << SDL_GetError() << std::endl;
return texture;
}
int RenderWindow::getRefreshRate()
{
int displayIndex = SDL_GetWindowDisplayIndex(window);
SDL_DisplayMode mode;
SDL_GetDisplayMode(displayIndex, 0, &mode);
return mode.refresh_rate;
}
void RenderWindow::cleanUp()
{
SDL_DestroyWindow(window);
}
void RenderWindow::clear()
{
SDL_RenderClear(renderer);
}
void RenderWindow::render(Entity& p_entity)
{
SDL_Rect src;
src.x = p_entity.getCurrentFrame().x;
src.y = p_entity.getCurrentFrame().y;
src.w = p_entity.getCurrentFrame().w;
src.h = p_entity.getCurrentFrame().h;
SDL_Rect dst;
dst.x = p_entity.getPos().x * 4;
dst.y = p_entity.getPos().y * 4;
dst.w = p_entity.getCurrentFrame().w * 4;
dst.h = p_entity.getCurrentFrame().h * 4;
SDL_RenderCopy(renderer, p_entity.getTex(), &src, &dst);
}
// void RenderWindow::freeTexture(SDL_Texture* p_tex) {
// SDL_DestroyTexture(p_tex);
// }
void RenderWindow::display()
{
SDL_RenderPresent(renderer);
}
Entity.hpp:
#pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Math.hpp"
class Entity
{
public:
Entity(Vector2f p_pos, SDL_Texture* p_tex);
Vector2f& getPos()
{
return pos;
}
void setPos(Vector2f p_pos)
{
pos = p_pos;
}
SDL_Texture* getTex();
SDL_Rect getCurrentFrame();
private:
Vector2f pos;
SDL_Rect currentFrame;
SDL_Texture* tex;
};
entity.cpp:
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Entity.hpp"
#include "Math.hpp"
Entity::Entity(Vector2f p_pos, SDL_Texture* p_tex)
:pos(p_pos), tex(p_tex)
{
currentFrame.x = 0;
currentFrame.y = 0;
currentFrame.w = 32;
currentFrame.h = 32;
}
SDL_Texture* Entity::getTex()
{
return tex;
}
SDL_Rect Entity::getCurrentFrame()
{
return currentFrame;
}
math.hpp:
#pragma once
#include <iostream>
struct Vector2f
{
Vector2f()
:x(0.0f), y(0.0f)
{}
Vector2f(float p_x, float p_y)
:x(p_x), y(p_y)
{}
void print()
{
std::cout << x << ", " << y << std::endl;
}
float x, y;
};
Utils.hpp:
#pragma once
#include <SDL2/SDL.h>
namespace utils
{
inline float hireTimeInSeconds()
{
float t = SDL_GetTicks();
t *= 0.001f;
return t;
}
}
Thanks!
This is an updated version of my code, i've figured it out.
It turns out the problem was:
if (frameTicks < 1000 / window.getRefreshRate())
SDL_Delay(100 / window.getRefreshRate() - frameTicks);
was actually delaying it by 100 instead of 1000.

c++ sfml - changing the sprite isn't working

I was working on changing sprite in my SFML project but it just doesn't want to wark. I tried everything - pointers, refrences and normal string objects. You can see in debug console i printed out this->path that containted a path to file to change but when it left the function this->path was null (empty "" string). Can you please help me? Here's the code:
Player.cpp
#include "Player.h"
#include <iostream>
Player::Player(std::string path)
{
this->path = path;
texture.loadFromFile(path);
sprite.setTexture(texture);
sprite.setPosition(500.f, 700.f);
}
void Player::update()
{
// Movement //
//if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
//sprite.move(0.f, -velocity);
//if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
//sprite.move(0.f, velocity);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
sprite.move(-velocity, 0.f);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
sprite.move(velocity, 0.f);
// Movement //
float szerokosc = sprite.getGlobalBounds().width;
float wysokosc = sprite.getGlobalBounds().height;
// Collision with screen //
// Left
if (sprite.getPosition().x < 0.f)
sprite.setPosition(0.f, sprite.getPosition().y);
// Top
if (sprite.getPosition().y < 0.f)
sprite.setPosition(sprite.getPosition().x, 0.f);
// Right
if (sprite.getPosition().x + szerokosc > 1000)
sprite.setPosition(1000 - szerokosc, sprite.getPosition().y);
// Bottom
if (sprite.getPosition().y + wysokosc > 800)
sprite.setPosition(sprite.getPosition().x, 800 - wysokosc);
// Collision with screen //
}
sf::Sprite Player::getSprite()
{
return sprite;
}
bool Player::collides(Food obj)
{
if (sprite.getGlobalBounds().intersects(obj.getSprite().getGlobalBounds()))
return true;
else
return false;
}
void Player::changeSkin(std::string path)
{
this->path = path;
std::cout << "changeSkin(): *this->path" << this->path << std::endl;
std::cout << "changeSkin(): *path" << path << std::endl;
texture.loadFromFile(path);
sprite.setTexture(texture);
}
void Player::updateSkin()
{
std::cout << "updateSkin() *this->path: " << this->path << std::endl;
std::cout << "updateSkin() *path: " << path << std::endl;
}
Player::~Player()
{
//delete texture;
//delete sprite;
}
Player.h
#pragma once
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <time.h>
#include "Food.h"
#include "ShopItem.h"
class Player
{
sf::Texture texture;
sf::Sprite sprite;
std::string path;
bool has_skin = false;
float velocity = 5.f;
public:
explicit Player(std::string path);
~Player();
void update();
sf::Sprite getSprite();
bool collides(Food obj);
void changeSkin(std::string path);
void updateSkin();
};
main.cpp - main() has Player::updateSkin() call
int main()
{
RenderWindow window(VideoMode(1000, 800), "Tomczyszyn Eater v0.21 BETA");
window.setFramerateLimit(60);
srand(time(nullptr));
Texture bg_text;
bg_text.loadFromFile("Assets/Textures/bg.png");
Sprite bg{ bg_text };
Player player{ "Assets/Textures/player.png" };
time_t start{};
Event event;
Intro* intro = new Intro{window};
MainMenu* menu = new MainMenu{&window};
Shop shop(&window);
Game game{player, &window};
bool intro_deleted{ false };
bool menu_deleted{ false };
bool game_started{ false };
int menuState{ 2 };
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == Event::EventType::Closed)
window.close();
if (Keyboard::isKeyPressed(Keyboard::Space) && game.gameRunning() == false)
{
start = time(nullptr);
game.runGame();
}
else if (Keyboard::isKeyPressed(Keyboard::Escape) && game.gameRunning() == false)
{
menuState = 0;
}
}
window.clear();
if (game.gameRunning() == true && menuState == 1) // Main Game
{
if (game_started == false)
{
start = time(nullptr);
game_started = true;
}
if (intro_deleted == false)
{
delete intro;
intro_deleted = true;
}
if (menu_deleted == false)
{
delete menu;
menu_deleted = true;
}
window.draw(bg);
game.drawMoney();
player.update();
window.draw(player.getSprite());
// Player::updateSkin() - source of the problem
player.updateSkin();
game.update();
game.draw();
if (time(nullptr) - start == 2)
{
start = time(nullptr);
int liczba = rand() % 6 + 1;
string file_name{ "Assets/Textures/food" + to_string(liczba) + ".png" };
Food* newFood = new Food{file_name};
game.spawn(newFood);
}
game.catched();
game.fell();
}
else if (menuState == 0) // Menu
{
if (menu_deleted == true) menu = new MainMenu{ &window };
menu->draw();
menu->update(menuState);
menu_deleted = false;
}
else if (menuState == -1) // Intro
{
start = time(nullptr);
intro->play();
if (intro->intro_started() == true) menuState = 0;
}
else if (menuState == 2) // Shop
{
shop.draw();
shop.backIfClicked(menuState);
shop.checkIfBought(player, game.balance());
game.drawMoney();
}
else
{
game.drawDeathScreen();
}
window.display();
}
}
Shop.cpp - checkIfBought() has Player::changeSkin() call
void Shop::checkIfBought(Player player, int& money)
{
for (int i = 0; i < skins.size(); i++)
{
if (isClicking(skins[i].getSprite()) == true)
{
skins[i].buy(money);
player.changeSkin(skins[i].getPath()); //Plaer::changeSkin() here - source of the problem
std::cout << skins[i].getPath() << std::endl;
}
}
for (int i = 0; i < bg_skins.size(); i++)
{
if (isClicking(bg_skins[i].getSprite()) == true)
{
bg_skins[i].buy(money);
player.changeSkin(bg_skins[i].getPath()); //Plaer::changeSkin() here - source of the problem
}
}
}
Debug Console output:
changeSkin(): this->path = Assets/Textures/skin1.png
changeSkin(): path = Assets/Textures/skin1.png
Assets/Textures/skin1.png
updateSkin() this->path = Assets/Textures/player.png
updateSkin() path = Assets/Textures/player.png
Sorry if you didn't understand my english is bad. I really do need help i've spent so much time on fixing this that i just gave up.

Objects in std::vector not saving attributes correctly

The problem I'm having is that when I change an attribute of an Object the change isn't 'saving'. Easier to show you what's happening.
I'm learning c++ and decided to build a small chess app. Each Piece is a seperate Object.
They're stored in a std::vector as such
std::vector<Piece> pieces;
They're initialised like so
for (int i = 0; i < 2; i++)
{
Piece p;
p.Init(i*2+1, 1, renderer, SQUARE_SIZE, "king");
pieces.push_back(p);
}
When I click the mouse I want to select all pieces (temporarily)
for (int i = 0; i < pieces.size(); i++)
{
Piece p = pieces[i];
p.Select();
}
The issue is that while the Select() function is being called, by the time I get to rendering their selected attribute is false. Strangely this does not happen to the piece not contained within in the vector, referred to as k.
Before you ask there is nowhere in my code that I set selected to false :) (Except the constructor :P )
Also if you feel like downvoting, send me a comment first and I'll try fix whatever it is!
Here are the entire files. (not sure if this is the proper way to insert them)
Piece.h
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDl_image.h>
#include <array>
#include <vector>
class Piece
{
public:
Piece();
void Init(int _x, int _y, SDL_Renderer* renderer, int SQUARE_SIZE, std::string type);
void SetPos(int _x, int _y, int _w);
void LoadTexture(SDL_Renderer* renderer, std::string type);
void LoadMovementVector(std::string type);
void Render(SDL_Renderer* renderer);
void Select(){ selected = true; std::cout << "called\n";}
bool isSelected(){ return selected; }
int GetX(){ return x; } // SDL_Point
int GetY(){ return y; }
private:
int x, y;
std::vector<int> move_vector;
bool selected;
SDL_Rect rect;
SDL_Texture* texture;
};
Piece.cpp
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDl_image.h>
#include <vector>
#include "Piece.h"
Piece::Piece()
: x(0)
, y(0)
, selected(false)
{
}
void Piece::Init(int _x, int _y, SDL_Renderer* renderer, int SQUARE_SIZE, std::string type)
{
SetPos(_x, _y, SQUARE_SIZE);
LoadTexture(renderer, type);
LoadMovementVector(type);
}
void Piece::Render(SDL_Renderer* renderer)
{
//selected = true;
//std::cout << selected << std::endl;
if (selected)
{
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &rect);
}
if (texture != nullptr)
{
SDL_RenderCopy(renderer, texture, nullptr, &rect);
}
else
{
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &rect);
}
}
void Piece::LoadMovementVector(std::string type)
{
if (type == "king"){ // There literally has to be a better way to init std::vector
int arr[4] = {1,1,1,0};
for (int i = 0; i < 4; i++){ move_vector.push_back(arr[i]); }
}
for (int i = 0; i < move_vector.size(); i++)
{
std::cout << move_vector[i];
}
std::cout << std::endl;
}
void Piece::LoadTexture(SDL_Renderer* renderer, std::string type)
{
std::string source;
if (type == "king"){
source = "wk.png";
}
texture = IMG_LoadTexture(renderer, "res/wk.png");
}
void Piece::SetPos(int _x, int _y, int _w)
{
x = _x;
y = _y;
rect.x = _w*(_x-1);
rect.y = _w*(8-_y);
rect.w = _w;
rect.h = _w;
std::cout << x << y << std::endl;
}
Main.cpp
#include <iostream>
#include <math.h>
#include <SDL2/SDL.h>
#include <SDL2/SDl_image.h>
#include "Piece.h"
using namespace std::chrono;
// Would be 'const int' but I want to make the board resizeable
int SCREEN_WIDTH = 800;
int SCREEN_HEIGHT = 800;
int BOARD_WIDTH, BOARD_HEIGHT, SQUARE_SIZE;
SDL_Window* window;
SDL_Renderer* renderer;
std::vector<Piece> pieces;
Piece k;
bool InitEverything();
bool InitSDL();
bool CreateWindow();
bool CreateRenderer();
void SetupRenderer();
void Quit();
void RunGame();
void Render();
void HandleInput();
void UpdateDimensions();
double GetDelta();
void RenderGameBoard();
bool loop = true;
auto timePrev = high_resolution_clock::now();
int main(int argc, char* args[])
{
if (!InitEverything())
return -1;
std::cout << "Running Game..." << std::endl;
for (int i = 0; i < 2; i++)
{
Piece p;
p.Init(i*2+1, 1, renderer, SQUARE_SIZE, "king");
pieces.push_back(p);
}
k.Init(5, 1, renderer, SQUARE_SIZE, "king");
RunGame();
Quit();
return 0;
}
void RunGame()
{
while (loop)
{
HandleInput();
Render();
double delta = GetDelta();
}
}
void Render()
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
RenderGameBoard();
for (int i = 0; i < pieces.size(); i++)
{
pieces[i].Render(renderer);
}
k.Render(renderer);
SDL_RenderPresent(renderer);
}
void RenderGameBoard()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if ((j%2==0&&i%2==0)||(j%2!=0&&i%2!=0))
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
else
SDL_SetRenderDrawColor(renderer, 180, 180, 180, 255);
SDL_Rect r = {i*SQUARE_SIZE, j*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE};
SDL_RenderFillRect(renderer, &r);
}
}
}
void HandleInput()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
loop = false;
else if (event.type == SDL_KEYDOWN)
{
}
else if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button.button == SDL_BUTTON_LEFT)
{
k.Select();
for (int i = 0; i < pieces.size(); i++)
{
Piece p = pieces[i];
p.Select();
}
int x = floor(event.button.x/SQUARE_SIZE)+1;
int y = 8-floor(event.button.y/SQUARE_SIZE);
for (int i = 0; i < pieces.size(); i++)
{
Piece p = pieces[i];
if (p.GetX() == x && p.GetY() == y)
{
p.Select();
}
}
}
}
}
}
void UpdateDimensions()
{
BOARD_WIDTH = SCREEN_WIDTH;
BOARD_HEIGHT = SCREEN_HEIGHT;
SQUARE_SIZE = BOARD_WIDTH/8;
}
double GetDelta()
{
auto timeCurrent = high_resolution_clock::now();
auto timeDiff = duration_cast< nanoseconds >( timeCurrent - timePrev );
double delta = timeDiff.count();
delta /= 1000000000;
timePrev = timeCurrent;
return delta;
}
bool InitEverything()
{
if (!InitSDL())
return false;
if (!CreateWindow())
return false;
if (!CreateRenderer())
return false;
SetupRenderer();
UpdateDimensions();
return true;
}
bool InitSDL()
{
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "SDL failed to initialize : " << SDL_GetError() << std::endl;
return false;
}
return true;
}
bool CreateWindow()
{
window = SDL_CreateWindow("Chess", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!window)
{
std::cout << "Failed to create window : " << SDL_GetError() << std::endl;
return false;
}
return true;
}
bool CreateRenderer()
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer)
{
std::cout << "Failed to create renderer : " << SDL_GetError() << std::endl;
return false;
}
return true;
}
void SetupRenderer()
{
SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
}
void Quit()
{
SDL_DestroyWindow(window);
SDL_Quit();
}
This:
Piece p = pieces[i];
is creating a copy of the piece at index i in the vector.
Any methods you call after that are operating on the copy, not on the piece in the array.
Instead, take a reference to it:
Piece& p = pieces[i];
After that, p is a reference to element i in the vector and any operations you perform on it are performed on the vector element.

Snake Rectangle Vector Collision

I'm new to SFML and C++ so I'm trying to learn both at the same time. I've decided to write a Snake game. For my snakes body I am using a vector of RectangleShapes. I've drawn a berry in the center of the screen and I can detect when the head of my snake is in collision with the berry, however I have no idea how to test if the snake is colliding with itself.
I've thought about testing collision between the head of the snake against the entire vector of blocks, but this will always return true as the head of the snake is in collision with itself.
I would appreciate any suggestions and criticisms of my code, Thanks!
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <string>
#include <sstream>
using namespace sf;
constexpr int windowWidth{800}, windowHeight{600};
Vector2f blockLocation{0, 0};
struct Block
{
RectangleShape shape;
Vector2f blockSize{15,15};
Block(float posX, float posY)
{
shape.setPosition(posX, posY);
shape.setSize(blockSize);
shape.setFillColor(Color::Blue);
shape.setOutlineColor(Color::Green);
shape.setOutlineThickness(3);
}
};
struct Berry
{
CircleShape shape;
Berry(float posX, float posY)
{
shape.setPosition(posX, posY);
shape.setRadius(8);
shape.setFillColor(Color::Red);
shape.setOutlineColor(Color::Magenta);
shape.setOutlineThickness(3);
}
};
bool keyUp(void)
{
if(Keyboard::isKeyPressed(Keyboard::Key::Up)) return true;
return false;
}
bool keyDown(void)
{
if(Keyboard::isKeyPressed(Keyboard::Key::Down)) return true;
return false;
}
bool keyLeft(void)
{
if(Keyboard::isKeyPressed(Keyboard::Key::Left)) return true;
return false;
}
bool keyRight(void)
{
if(Keyboard::isKeyPressed(Keyboard::Key::Right)) return true;
return false;
}
int stat(std::vector<Block> *blocks, RenderWindow *window)
{
sf::Font font;
if(!font.loadFromFile("Oswald-Bold.ttf"))
{
std::cerr << "Cannot load font!" << std::endl;
return 1;
}
sf::Text text;
text.setFont(font);
std::ostringstream message;
message << "x: " << blockLocation.x << std::endl
<< "y: " << blockLocation.y << std::endl
<< "blocks: " << blocks->size() << std::endl;
text.setString(message.str());
text.setCharacterSize(24);
text.setColor(sf::Color::Magenta);
text.setOrigin(0, 0);
window->draw(text);
return 0;
}
bool collision(Block *shapeA, Berry *shapeB)
{
if( shapeA->shape.getGlobalBounds().intersects(shapeB->shape.getGlobalBounds()) )
{
std::cout << "collision with ";
std::cout << "x: " << shapeA->shape.getPosition().x << "y: " <<
shapeA->shape.getPosition().y << "and x: " << shapeB->shape.getPosition().x << "y: " << shapeB->shape.getPosition().y << std::endl;
return true;
}
else
return false;
}
int main(void)
{
Clock clock;
Time timeSinceLastUpdate = Time::Zero;
const Time TimePerFrame = seconds(3.0f/30.f);
std::vector<Block> blocks;
RenderWindow window{ {windowWidth, windowHeight} , "blocks!"};
bool up(false);
bool down(false);
bool left(false);
bool right(false);
window.setFramerateLimit(60);
Berry berry(400, 300);
blocks.emplace_back(blockLocation.x, blockLocation.y);
while(window.isOpen())
{
if(Keyboard::isKeyPressed(Keyboard::Key::Escape)) return 0;
Time elapsedTime = clock.restart();
timeSinceLastUpdate += elapsedTime;
while(timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
window.clear(Color::Black);
// Get the Head of the snake
auto first = blocks.back();
if(keyUp())
{
up = true;
down = false, left = false, right = false;
blocks.emplace_back(blockLocation.x, blockLocation.y);
blocks.erase(blocks.begin());
}
else if(keyDown())
{
down = true;
up = false, left = false, right = false;
blocks.emplace_back(blockLocation.x, blockLocation.y);
blocks.erase(blocks.begin());
}
else if(keyLeft())
{
left = true;
right = false, up = false, down = false;
blocks.emplace_back(blockLocation.x, blockLocation.y);
blocks.erase(blocks.begin());
}
else if(keyRight())
{
right = true;
left = false, up = false, down = false;
blocks.emplace_back(blockLocation.x, blockLocation.y);
blocks.erase(blocks.begin());
}
if(up) { blockLocation.y-=19; blocks.emplace_back(blockLocation.x, blockLocation.y); blocks.erase(blocks.begin());
}
if(down) { blockLocation.y+=19; blocks.emplace_back(blockLocation.x, blockLocation.y); blocks.erase(blocks.begin());
}
if(left) { blockLocation.x-=19; blocks.emplace_back(blockLocation.x, blockLocation.y); blocks.erase(blocks.begin());
}
if(right){ blockLocation.x+=19; blocks.emplace_back(blockLocation.x, blockLocation.y); blocks.erase(blocks.begin());
}
if (collision(&first, &berry)) blocks.emplace_back(blockLocation.x, blockLocation.y);
if(blocks.size() > 50)
{
blocks.erase(blocks.begin());
}
for(auto a : blocks)
{
window.draw(a.shape);
}
window.draw(berry.shape);
stat(&blocks, &window);
window.display();
}
}
return 0;
}

Trouble changing class variable

I'm trying to write a small game where boxes drop down from the top of the window. But for some reason, I can't change a internal variable in the class, the y-coordinate. I don' knowif I'm missing something basic, but I can't find the bug.
Box.h
#pragma once
#include "SDL.h"
class Box
{
public:
Box();
~Box();
void setX (int a);
void setY (int a);
void setSpeed (int a);
void setSurface ();
void render(SDL_Surface *source, SDL_Window *win);
void update();
private:
int x;
int y;
int speed;
SDL_Surface *sur;
SDL_Rect rect;
};
Box.cpp
#include "Box.h"
#include "SDL_image.h"
#include <iostream>
void Box::setX(int a)
{
x = a;
}
void Box::setY (int a)
{
y = a;
}
void Box::setSpeed (int a)
{
speed = a;
}
void Box::setSurface()
{
sur = IMG_Load("C:/hello.bmp");
if (sur == NULL)
{
std::cout << IMG_GetError();
}
}
Box::Box()
{
speed = 5;
y = 0;
x = 3;
rect.x = 0;
rect.y = 0;
}
Box::~Box()
{
}
void Box::render(SDL_Surface *source, SDL_Window *win)
{
SDL_BlitSurface(sur, NULL, source, &rect);
SDL_UpdateWindowSurface(win);
}
void Box::update()
{
setY(y + speed); //I've also tried y = y + speed
rect.y = y;
}
main.cpp
#include "SDL.h"
#include "Box.h"
#include "SDL_image.h"
#include <iostream>
bool init();
void update(Box test);
void render(Box test);
SDL_Window *win;
SDL_Surface *source;
int main(int argc, char *argv[])
{
init();
bool quit = false;
SDL_Event e;
Box test;
test.setSurface();
test.render(source, win);
while (quit ==false)
{
while( SDL_PollEvent( &e ) != 0 )
{
if( e.type == SDL_QUIT )
{
quit = true;
}
}
update(test);
render(test);
}
return 0;
}
void update(Box test)
{
test.update();
}
void render(Box test)
{
test.render(source, win);
}
bool init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
if (win == NULL)
{
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
source = SDL_GetWindowSurface(win);
return true;
}
update takes its Box argument by value, so a copy of the original Box is always made when update(test) is called. This copy is then modified, and the original is left unchanged. To fix this, make update take its argument by reference.
void update(Box& test);
void update(Box& test)
{
test.update();
}