Code::Blocks executable file doesn't have textures - c++

I've made a basic program using the SFML library in Code::Blocks, and now all I want to do is send it to a friend. I've built my program in both debug and release mode, yet whenever I run the .exe file from my bin, it simply will not load the textures. Of course when I run it within the Code::Blocks client, it works perfectly. I'm not sure if I need to package my work or send the files separately or what, but any help would be much appreciated
Here's the code in case it's helpful somehow (I know it's not pretty):
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <string>
#include <iostream>
#include <Windows.h>
int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "Enjoy :)");
sf::Clock clock;
int pixelFindX = 0, pixelFindY = 0;
int oldLoc = 0, newLoc = 0;
int changeVal = 1;
int tripleCheck = 0;
int xLoc = 0, yLoc = 100;
double timeChecker = 0;
bool execute = false, secondExecute = false;
bool oldSide = false, newSide = false, changer = true;
bool drawLeft = false, drawRight = false, drawCenter = false;
sf::Texture pTexture;
sf::Sprite playerImage;
if(!pTexture.loadFromFile("Pixel Dude.png")){
std::cout << "Could not load pTexture file" << std::endl;
}
sf::Texture bTexture;
sf:: Sprite backgroundImage;
if(!bTexture.loadFromFile("molester moon background IS DONE.jpg")){
std::cout << "Could not load bTexture file" << std::endl;
}
sf::Texture bridgeTexture;
sf::Sprite bridgeImageL;
sf::Sprite bridgeImageR;
if(!bridgeTexture.loadFromFile("pixel bridge.jpg")){
std::cout << "Could not load bridgeTexture file" << std::endl;
}
sf::Texture trophyTexture;
sf::Sprite trophyImage;
if(trophyTexture.loadFromFile("trophy pixeled.png")){
std::cout << "Could not load trophyTexture file" << std::endl;
}
sf::String stringL = "Move to the Left!", stringR = "Move to the Right!", stringC = "You are currently balanced.";
sf::String stringGo = stringL;
sf::Font font;
if(!font.loadFromFile("arial.ttf")){
std::cout << "Could not load font file" << std::endl;
}
sf::Text text(stringGo, font, 50);
text.setPosition(xLoc, yLoc);
text.setStyle(sf::Text::Bold);
playerImage.setTexture(pTexture);
playerImage.setPosition(336, 355);
playerImage.setScale(4,4);
playerImage.setTextureRect(sf::IntRect(pixelFindX*32, pixelFindY*32, 32, 32));
backgroundImage.setTexture(bTexture);
backgroundImage.setPosition(0,0);
bridgeImageL.setTexture(bridgeTexture);
bridgeImageL.setPosition(0, 450);
bridgeImageL.setScale(4.17,4.68);
bridgeImageR.setTexture(bridgeTexture);
bridgeImageR.setPosition(400,450);
bridgeImageR.setScale(4.17, 4.68);
trophyImage.setTexture(trophyTexture);
trophyImage.setPosition(600, 305);
trophyImage.setScale(2,2);
sf::View view;
sf::View viewReg;
view.reset(sf::FloatRect(0, 0, 800, 600));
view.setViewport(sf::FloatRect(0, 0, 1, 1));
viewReg.reset(sf::FloatRect(0, 0, 800, 600));
viewReg.setViewport(sf::FloatRect(0, 0, 1, 1));
std::cout << "Player Dimensioms: Width = " << playerImage.getGlobalBounds().width << ", Height = " << playerImage.getGlobalBounds().height << std::endl;
while(Window.isOpen()){
clock.restart();
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;
}
}
//std::cout << timeChecker << std::endl;
timeChecker += clock.getElapsedTime().asSeconds();
if(timeChecker >= .00025){
execute = true;
timeChecker = 0;
//std::cout << "execute = true" << std::endl;
}
oldLoc = playerImage.getPosition().x;
oldSide = changer;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D) && execute){
playerImage.move(1, 0);
pixelFindY = 2;
tripleCheck++;
changer = true;
//std::cout << "d called" << std::endl;
} else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A) && execute){
playerImage.move(-1, 0);
pixelFindY = 1;
tripleCheck++;
changer = false;
//std::cout << "a called" << std::endl;
}
if(playerImage.getPosition().x < -96){
playerImage.setPosition(800, playerImage.getPosition().y);
} else if(playerImage.getPosition().x > 800){
playerImage.setPosition(-96, playerImage.getPosition().y);
}
newLoc = playerImage.getPosition().x;
newSide = changer;
pixelFindX += changeVal;
if(pixelFindX > 2){
pixelFindX -= 2;
changeVal = -1;
} else if(pixelFindX < 0){
pixelFindX += 2;
changeVal = 1;
}
if(oldLoc != newLoc && tripleCheck > 40 || oldSide != newSide){
playerImage.setTextureRect(sf::IntRect(pixelFindX*32, pixelFindY*32, 32, 32));
tripleCheck = 0;
//std::cout << "Yes called, pixelFindX = " << pixelFindX << ", tripleCheck = " << tripleCheck << std::endl;
} else {
//std::cout << "-----Not called, pixelFindX = " << pixelFindX << ", tripleCheck = " << tripleCheck << std::endl;
}
execute = false;
/* if(playerImage.getPosition().x + 128 > trophyImage.getPosition().x && playerImage.getPosition().x < trophyImage.getPosition().x + 192){
view.rotate(.0001);
}
*/
if(playerImage.getPosition().x > 500 - 128){
view.rotate(-.01);
drawRight = true;
} else if (playerImage.getPosition().x < 300 - 128){
view.rotate(.01);
drawLeft = true;
} else{
drawCenter = true;
}
//std::cout << "Player X: " << playerImage.getPosition().x + 128 << ", Trophy X: " << trophyImage.getPosition().x << std::endl;
if(drawLeft){
stringGo = stringR;
xLoc = 0;
} else if (drawRight){
stringGo = stringL;
xLoc = 800 - text.getGlobalBounds().width - 10;
} else if(drawCenter){
stringGo = stringC;
xLoc = 400 - text.getGlobalBounds().width / 2;
}
text.setPosition(xLoc, yLoc);
text.setString(stringGo);
Window.setView(viewReg);
Window.draw(backgroundImage);
Window.draw(text);
Window.setView(view);
Window.draw(bridgeImageL);
Window.draw(bridgeImageR);
// Window.draw(trophyImage);
Window.draw(playerImage);
Window.display();
Window.clear();
drawLeft = false;
drawRight = false;
drawCenter = false;
//Sleep(50);
}
}

Copy the compiled executable into a new folder and paste there the textures too. This folder you can send your friend (e.g. in a rar-archive).The textures won't load because probably the textures weren't in the bin/debug or bin/release folder. There are in another place wich is in the debugging mode is set as the working directory.If you want to change that (what I would not recommend) you can go to Project -> Properties -> Build targets -> [name of target] -> Execution working dir and change it to the directory where the compiled executables went.

Related

SetWindowPos() sometimes does not resize child-windows

First, I use Createprocess() to open all desired windows. (Not Listed)
After the successful opening of the processes I find with the FindWindow () and FindWindowEx() all available windows. (Listed)
Sometimes the function SetWindowPos() does not work properly. A few windows were sorted out a few not. But this case does not always occur!
For improvements I always have an open ear!
//Some Variables comming from other code : numberOfWindows / numberOfStartedWindows
//Variables
bool trigger = true;
bool targetProcess = true;
HWND hwnd, hwndChilds = NULL;
int targetsFound = 0;
int targetsFoundMath = 0;
bool searchWindows = true;
//Start targetProcess
while (targetProcess) {
//If targetsFround == numberOfWindows then exit targetProcess.
if (targetsFound == numberOfWindows)
{
targetProcess = false;
}
//If all Windows are Started then start search loop
if (numberOfStartedWindows == numberOfWindows)
{
trigger = false;
}
//We starting search loop...
if (!trigger && targetProcess) {
//Find the Main Window.
hwnd = FindWindow(0, _T("World of Warcraft"));
if (hwnd)
{
targetsFound += 1;
//Set Window Foreground and call SetWindowPos to change Position
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
{
cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
}
}
//Store HWND in StoreWindows
StoreWindows.emplace_back(hwnd);
//Now we search for child Windows
while (searchWindows)
{
//do it if targetsFound not numberOfWindows
if (targetsFound != numberOfWindows)
{
//Get Child Window
hwndChilds = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
if (hwndChilds != NULL)
{
//Little Math for Position
targetsFoundMath = (targetsFound - 1) * 384;
//if window in foreground SetWindowPos.
if(SetForegroundWindow(hwndChilds)){
if (!SetWindowPos(hwndChilds, HWND_TOP, targetsFoundMath, 800, 384, 280, SWP_SHOWWINDOW))
{
cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
}
}
/*targetsFound += 1;
StoreWindows.emplace_back(hwndChilds);*/
//If all targetsFound then quit this loop after finish
if (targetsFound == numberOfWindows) {
searchWindows = false;
cout << "false" << targetsFound << endl;
}
//StoreChild Window and Add targetsfround +1
targetsFound += 1;
StoreWindows.emplace_back(hwndChilds);
}
else {
searchWindows = false;
cout << "no more child objects found!" << endl;
}
}
else
{
searchWindows = false;
}
}
}
}
}
cout << "Window Size: " << StoreWindows.size() << endl;
Funny when I debugs:
RECT debugRect;
for (int x = 0; x < StoreWindows.size(); x++)
{
GetClientRect(StoreWindows[x], &debugRect);
cout << debugRect.left << " " << debugRect.right<< " " << debugRect.bottom<< " " << debugRect.top << endl;
//debugRect.right = breite vom fenster // debugRect.bottom = Höhe
}
The output from the Position looks good but the Window isnt on the right place :/
Debug:
Im out of ideas and hope you can help me! If you need more explanations, do not hesitate to ask.
With problems it looks so..
If everything goes without problems it looks like this:
The problem was the duplicate (same) window partial to be found. Because the start process takes longer than the Find Func. Now i have Fixxed the loop. (Its wait now for all success windows.)
bool mainWindow = false;
bool searchHwndStrike = false;
int targetResult = 0;
while (true)
{
//Search first Window
if (!mainWindow) {
hwnd = FindWindow(0, _T("World of Warcraft"));
if (hwnd != NULL)
{
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
{
cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
}
}
cout << "Main window found." << endl;
mainWindow = true;
StoreWindows.emplace_back(hwnd);
}
}else {
if (StoreWindows.size() < numberOfWindows) {
hwnd = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
if (hwnd != NULL)
{
for (int x = 0; x < StoreWindows.size(); x++)
{
if (StoreWindows[x] == hwnd)
{
searchHwndStrike = true;
}
}
if (!searchHwndStrike)
{
cout << "Child window found." << endl;
cout << targetResult << endl;
targetResult = (StoreWindows.size()-1) * 384;
//if window in foreground SetWindowPos.
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, targetResult, 800, 384, 280, SWP_SHOWWINDOW))
{
cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
}
}
StoreWindows.emplace_back(hwnd);
}
searchHwndStrike = false;
}
}
else {
break;
}
}
}
cout << StoreWindows.size() << endl;

SFML Bullet not spawning

So I am using SFML and c++ to create a simple space game. For the life of can't get a bullet to spawn. This is my source... I am just trying to learn how to go about spawning new sprites into a game.
```
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <string>
int main()
{
// Create the main window
sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window");
// Load a sprite to display
sf::Texture texture_sprite;
if (!texture_sprite.loadFromFile("cb.bmp"))
return EXIT_FAILURE;
sf::Sprite sprite(texture_sprite);
sf::Texture texture_background;
if (!texture_background.loadFromFile("space.png"))
return EXIT_FAILURE;
sf::Sprite background(texture_background);
sf::Texture texture_fire;
if (!texture_background.loadFromFile("fire_1.png"))
return EXIT_FAILURE;
sf::Sprite fire_sprite(texture_fire);
fire_sprite.setScale(4.0f, 1.6f);
std::string direction = "";
bool fire = false;
// Start the game loop
while (app.isOpen())
{
// Process events
sf::Event event;
while (app.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
app.close();
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && sprite.getPosition().x > -20)
{
sprite.move(-10,0);
std::cout << "X = " << sprite.getPosition().x << std::endl;
std::cout << "Y = " << sprite.getPosition().y << std::endl;
direction = "Left";
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && sprite.getPosition().x < 670 )
{
sprite.move(10,0);
std::cout << "X = " << sprite.getPosition().x << std::endl;
std::cout << "Y = " << sprite.getPosition().y << std::endl;
direction = "Right";
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && sprite.getPosition().y > 0)
{
sprite.move(0,-10);
std::cout << "X = " << sprite.getPosition().x << std::endl;
std::cout << "Y = " << sprite.getPosition().y << std::endl;
direction = "Up";
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && sprite.getPosition().y < 480 )
{
sprite.move(0,10);
std::cout << "X = " << sprite.getPosition().x << std::endl;
std::cout << "Y = " << sprite.getPosition().y << std::endl;
direction = "Down";
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
{
fire = true;
}
else if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Space)
{
fire = false;
}
if(fire == true)
{
std::cout << "FIRE!!!" << std::endl;
fire_sprite.setPosition((sprite.getPosition()));
std::cout << "Fire positions is " <<fire_sprite.getPosition().x << " " << fire_sprite.getPosition().y << "The direction is " << direction <<std::endl;
}
}
app.clear();
// Draw the sprite
app.draw(background);
app.draw(sprite);
app.draw(fire_sprite);
// Update the window
app.display();
}
return EXIT_SUCCESS;
}
```
sf::Texture texture_fire;
if (!texture_background.loadFromFile("fire_1.png"))
Instead of loading texture to texture_fire you load again to texture_background. It should be:
if (!texture_fire.loadFromFile("fire_1.png"))

TTF_RenderText_Solid() Crashing Game and Visual Studio [c++][sdl ttf]

Stack Trace :
So, I'm trying to create a 2D game and right now I'm trying to display and move a image, however when I Debug the game/run it, visual studio and the game freezes and can't quit, not even when using the task manager to kill it.
The only way to unfreeze it is by logging off or restarting the pc which forces both of them to close.
I also get some weird error :
Unhandled exception at 0x71002A95 (SDL2_ttf.dll) in SDLGame.exe: 0xC0000005: Access violation reading location 0x00000000.
I have no idea what it means and how to fix it, but I'm guessing it has something to do with my code that I need to change.
Here's my code :
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
// Macros
#define pause system("PAUSE"); // Works on windows only, removed in alpha / beta versions.
// Pre "init" of functions
void QuitGame();
int InitGame();
void processInput();
void InitRects();
// Variables
int FramesPassed = 0;
int FramesPerSecond = 0; // Not used yet
SDL_Renderer* renderer = nullptr;
SDL_Window* window = nullptr;
SDL_Event evnt;
SDL_Rect sprite1_Rect;
SDL_Rect FPS_Text_Rect;
TTF_Font* Sans = TTF_OpenFont("Fonts/Aaargh.ttf", 40);
SDL_Color Color_White = { 255, 255, 255 };
SDL_Surface* FPS_Text_Surface = nullptr;
SDL_Texture* FPS_Text = nullptr;
SDL_Texture* testImg = nullptr;
static bool isRunning = true;
int SDL_main(int argc, char* argv[])
{
InitGame();
InitRects();
std::cout << "Displaying text on screen using SDL TTF doesn't work" << std::endl;
std::cout << "This happens when the TTF Surface is being rendered on screen" << std::endl;
std::cout << "check line : 123 and 124." << std::endl;
while (isRunning)
{
FramesPassed++;
processInput();
SDL_RenderClear(renderer); // Clears the last/current frame?
// Render testImage on screen. (needs to be between render present and clear.)
SDL_RenderCopy(renderer, testImg, NULL, &sprite1_Rect);
SDL_RenderCopy(renderer, FPS_Text, NULL, &FPS_Text_Rect);
SDL_RenderPresent(renderer); // Pretty much draws everything again.
}
return 0;
QuitGame();
}
int InitGame()
{
std::cout << "Game Initializing..." << std::endl;
std::cout << "TTF SDL Initializing..." << std::endl;
if (TTF_Init() < 0)
{
std::cout << "SDL TTF Failed To Initialize : " << TTF_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL TTF Initialized Successfully" << std::endl;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "SDL Initialization Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initializing" << std::endl;
window = SDL_CreateWindow("Game Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 720, SDL_WINDOW_SHOWN);
if (window == NULL)
{
std::cout << "Window Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initialized Successfully" << std::endl;
std::cout << "Renderer Initializing..." << std::endl;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
std::cout << "Renderer Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "Renderer Initialized Successfully" << std::endl;
// This line (under) crashes game, and crashes visual studio...
FPS_Text_Surface = TTF_RenderText_Solid(Sans, "Frames Passed : " + FramesPassed, Color_White);
testImg = IMG_LoadTexture(renderer, "images/test.bmp");
FPS_Text = SDL_CreateTextureFromSurface(renderer, FPS_Text_Surface);
}
}
}
}
std::cout << "Game Has Successfully Initialized!" << std::endl;
return 0;
}
void InitRects()
{
sprite1_Rect.h = 32;
sprite1_Rect.w = 32;
sprite1_Rect.x = 10;
sprite1_Rect.y = 10;
FPS_Text_Rect.h = 100;
FPS_Text_Rect.w = 50;
FPS_Text_Rect.x = 2;
FPS_Text_Rect.y = 2;
}
void processInput()
{
if (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
QuitGame();
break;
case SDL_KEYDOWN:
switch (evnt.key.keysym.sym) {
case SDLK_a:
sprite1_Rect.x -= 1;
break;
case SDLK_d:
sprite1_Rect.x += 1;
break;
case SDLK_w:
sprite1_Rect.y-= 1;
break;
case SDLK_s:
sprite1_Rect.y += 1;
break;
}
break;
}
}
}
void QuitGame()
{
isRunning = false;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
The problem is that you have the font as a global variable and load it straight away!
You need to call TTF_Init() first and load the font after!
By using a global vairable your loading it before initializing SDL_TTF, and this way TTF_OpenFont() will return a nullptr and if you try to read a nullptr gives an Access violation reading location 0x00000000 error!
Just call TTF_OpenFont() in a function and after TTF_Init() and it will work!
Just a tip you should check that Sans isn't a nullptr before using it!

Error with bullets spawn in SFML

I have a little problem with spawning bullets in my SFML game.
There's code:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <cmath>
int pad_id;
int pociski = 3;
int d_pad_x, d_pad_y;
int klatki;
bool p_1;
bool p_2;
bool p_3;
sf::Texture tekstura, pocisk;
sf::Sprite kulka, pocisk_1, pocisk_2, pocisk_3;
sf::Clock _clock;
float accumulator = 0;
float TIME_STEP = 0.03f;
sf::ContextSettings settings;
sf::RenderWindow window(sf::VideoMode(1920, 1080), "Wrecking balls", sf::Style::Fullscreen, settings);
class bullet
{
public:
sf::Texture bullet_texture;
sf::Sprite _sprite;
void spawn_new_bullet(sf::Vector2f from, sf::Vector2f to);
};
void bullet::spawn_new_bullet(sf::Vector2f from, sf::Vector2f to)
{
bullet_texture.loadFromFile("pocisk.png");
_sprite.setTexture(bullet_texture);
_sprite.setPosition(from);
_sprite.setRotation(atan2(to.y - from.y, to.x - from.x));
window.draw(_sprite);
}
int main()
{
settings.antialiasingLevel = 2;
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(true);
if(!tekstura.loadFromFile("ball.png"))
{
std::cout << "error" << std::endl;
}
if (!pocisk.loadFromFile("pocisk.png"))
{
std::cout << "error" << std::endl;
}
kulka.setTexture(tekstura);
pocisk_1.setTexture(pocisk);
pocisk_2.setTexture(pocisk);
pocisk_3.setTexture(pocisk);
for (int i=0; i<8; i++)
{
if (sf::Joystick::isConnected(i))
{
std::cout << "Pad " << i << " is connected." << std::endl << "Number of buttons: " << sf::Joystick::getButtonCount(i) << std::endl;
pad_id = i;
}
}
kulka.setScale(0.050, 0.050);
pocisk_1.setScale(0.050, 0.050);
pocisk_2.setScale(0.050, 0.050);
pocisk_3.setScale(0.050, 0.050);
while (window.isOpen())
{
accumulator += _clock.restart().asSeconds();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
if (event.type == sf::Event::JoystickButtonPressed)
{
if (sf::Joystick::isButtonPressed(0, 0))
{
std::cout << "0" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 1))
{
std::cout << "1" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 2))
{
std::cout << "2" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 3))
{
std::cout << "3" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 4))
{
std::cout << "4" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 5))
{
std::cout << "5" << std::endl;
if (pociski > 0)
{
if (pociski == 3)
{
p_3 = true;
}
if (pociski == 2)
{
p_2 = true;
}
if (pociski == 1)
{
p_1 = true;
}
pociski -= 1;
}
}
if (sf::Joystick::isButtonPressed(0, 6))
{
std::cout << "6" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 7))
{
std::cout << "7" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 8))
{
std::cout << "8" << std::endl;
}
if (sf::Joystick::isButtonPressed(0, 9))
{
std::cout << "9" << std::endl;
}
}
}
if(accumulator > TIME_STEP)
{
window.clear();
if (pociski < 3)
{
klatki += 1;
}
d_pad_x = sf::Joystick::getAxisPosition(pad_id, sf::Joystick::X);
d_pad_y = sf::Joystick::getAxisPosition(pad_id, sf::Joystick::Y);
kulka.move(d_pad_x / 5, d_pad_y / 5);
pocisk_1.setPosition(kulka.getPosition().x + 10, kulka.getPosition().y + 13.75);
pocisk_2.setPosition(kulka.getPosition().x + 20, kulka.getPosition().y + 13.75);
pocisk_3.setPosition(kulka.getPosition().x + 30, kulka.getPosition().y + 13.75);
//std::cout << d_pad_x << d_pad_y << std::endl;
window.draw(kulka);
if (pociski == 1)
{
window.draw(pocisk_1);
}
else if (pociski == 2)
{
window.draw(pocisk_1);
window.draw(pocisk_2);
}
else if (pociski == 3)
{
window.draw(pocisk_1);
window.draw(pocisk_2);
window.draw(pocisk_3);
}
if (p_3 == true)
{
bullet::spawn_new_bullet(kulka.getPosition(), sf::Vector2(100, 100));
p_3 = false;
}
if (p_2 == true)
{
bullet::spawn_new_bullet(kulka.getPosition(), sf::Vector2(100, 100));
p_2 = false;
}
if (p_1 == true)
{
bullet::spawn_new_bullet(kulka.getPosition(), sf::Vector2(100, 100));
p_1 = false;
}
accumulator -= TIME_STEP;
window.display();
}
if (klatki >= 166)
{
if (pociski < 3)
{
pociski += 1;
klatki = 0;
}
}
}
return 0;
}
The error I got in line 162 is: "missing template arguments before '(' token". Can anyone tell me what I should do? And why this method has to be used with a template?
Vector2 is a template type. Either provide the template parameters, or use one of the provided typedefs such as sf::Vector2i – Neil Kirkckquote
Give correct second argument to your function spawn_new_bullet, for example Vector2f().
Cheer!

SDL blit surface: Segmentation fault

Every time I run this program I got a this error:
Segmentation fault
testing.cpp
#include <iostream>
#include <cstdint>
#include <SDL.h>
#include <SDL_image.h>
#include "Surface.h"
#include "Point2D.h"
int main() {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
std::cerr << "Can not init SDL" << std::endl;
return -1;
}
SDL_Surface *scr = SDL_SetVideoMode(800, 600, 0, SDL_HWSURFACE | SDL_DOUBLEBUF);
if ( scr == NULL ) {
std::cerr << "Can not open window" << std::endl;
return -1;
}
SDL_WM_SetCaption("Test Surface class", NULL);
Surface screen;
Surface image;
screen.set(SDL_GetVideoSurface());
if (image.load("./data/images/logo.png") == false) {
std::cerr << "Can not open file" << std::endl;
return -1;
}
bool run = true;
uint32_t sticks = SDL_GetTicks();
while(run) {
if (screen.draw(image, Rectangle(0, 0, image.getWidth(), image.getHeight()), Point2D(0, 0)) == false) {
std::cerr << "Can not draw to window" << std::endl;
return -1;
}
if ((SDL_GetTicks() - sticks)/1000 > 5) {
std::cerr << "End of time" << std::endl;
run = false;
}
SDL_Flip(screen.sdlSurface());
}
std::cerr << "Done" << std::endl;
SDL_Quit();
return 0;
}
There is the source code of class Surface
#include "Surface.h"
#include "Color.h"
Surface::Surface() {
this->surface = NULL;
}
Surface::~Surface() {
SDL_FreeSurface(this->surface);
this->surface = NULL;
}
bool Surface::draw(Surface source, Rectangle source_area, Point2D position) {
SDL_Rect sr = source_area.sdlRect();
SDL_Rect tr = {position.getX(), position.getY(), 0, 0};
std::cout << sr.x << "," << sr.y << "," << sr.w << "," << sr.h << std::endl;
std::cout << tr.x << "," << tr.y << "," << tr.w << "," << tr.h << std::endl;
std::cout << source.sdlSurface() << std::endl;
std::cout << this->surface << std::endl;
// TR and SR are currently unused. Just for case of testing
if (SDL_BlitSurface(source.sdlSurface(), NULL, this->surface, NULL) != 0) {
return false;
}
return true;
}
bool Surface::fill(Color color, Rectangle area) {
SDL_Rect tr = area.sdlRect();
std::cout << tr.x << "," << tr.y << "," << tr.w << "," << tr.h << std::endl;
std::cout << (int)color.sdlColor() << std::endl;
if ( SDL_FillRect(this->surface, &tr, color.sdlColor()) != 0) {
return false;
}
return true;
}
Rectangle Surface::getSize() {
return Rectangle(0, 0, this->getWidth(), this->getHeight());
}
bool Surface::load(std::string file) {
SDL_Surface *src = IMG_Load(file.c_str());
if (src == NULL) {
std::cout << "cyh" << std::endl;
std::cout << IMG_GetError() << std::endl;
return false;
}
this->surface = SDL_DisplayFormatAlpha(src);
if (this->surface == NULL) {
std::cout << "cyh1" << std::endl;
std::cout << SDL_GetError() << std::endl;
return false;
}
SDL_FreeSurface(src);
src = NULL;
return true;
}
void Surface::set(SDL_Surface *surface) {
this->surface = surface;
}
void Surface::set(Surface surface) {
this->surface = surface.sdlSurface();
}
The problem is probably in the draw function. If I change this line:
if (SDL_BlitSurface(source.sdlSurface(), NULL, this->surface, NULL) != 0) {
to:
if (SDL_BlitSurface(IMG_Load("./data/images/logo.png"), NULL, this->surface, NULL) != 0) {
everything seems to be ok. Could you give me a suggestion where should be the problem?
You're violating The Rule of 3.
You need to define a copy constructor and a copy assignment operator for this to work properly.
When you're passing the Surface in to the draw method, you're making a copy of it. Since you're managing a resource inside the Surface class (the SDL_Surface*), you'll have multiple instances of the class pointing at the same surface, so when the destructors are called, you'd be freeing the same SDL_Surface* more than once.
Edit: I would recommend passing your arguments by const reference. You don't need to make copies of the Surface objects when you want to draw them.
This:
bool Surface::draw(Surface source, Rectangle source_area, Point2D position);
Would become this:
bool Surface::draw(const Surface &source, const Rectangle &source_area, const Point2D &position);
And this can be applied to your other functions too.