I'm new to c++ so I'm a bit confused on this one. I'm trying to have the player spawn, then when the user presses "C", the player switches with a car. What's happening currently is the player is initially spawning in the correct location, then the car is spawning where the player initially spawned, not where it currently is. However, since I'm using the function getPosition(), I would assume it would spawn in the current position of the player.
Player.h:
#pragma once
#include <SFML\Graphics.hpp>
#include <string>
class player {
public:
sf::Texture normalTexture;
sf::Sprite normalSprite;
sf::Texture carTexture;
sf::Sprite carSprite;
sf::Texture springTexture;
sf::Sprite springSprite;
sf::Texture rocketTexture;
sf::Sprite rocketSprite;
sf::IntRect normalRect[1];
sf::IntRect carRect[1];
sf::IntRect springRect[1];
sf::IntRect rocketRect[1];
bool rocket=false;
bool car=false;
bool spring=false;
bool normal=false;
player();
player(sf::Vector2f position, std::string normalFileLoc, std::string carFileLoc, std::string springFileLoc, std::string rocketFileLoc);
void update();
};
Player.cpp:
#include "Player.h"
player::player() : player::player(sf::Vector2f(100, 0), "player.jpg", "car.png", "spring.png", "rocket.png") {
}
player::player(sf::Vector2f position, std::string normalFileLoc, std::string
carFileLoc, std::string springFileLoc, std::string rocketFileLoc)
{
normalTexture.loadFromFile(normalFileLoc);
normalRect[0] = sf::IntRect(0, 0, 64, 128);
normalSprite.setTexture(normalTexture);
normalSprite.setTextureRect(normalRect[0]);
normalSprite.setOrigin(0,0);
normalSprite.setScale(1, 1);
normalSprite.setPosition(position.x, position.y);
carTexture.loadFromFile(carFileLoc);
carRect[0] = sf::IntRect(0, 0, 64, 64);
carSprite.setTexture(carTexture);
carSprite.setTextureRect(carRect[0]);
carSprite.setOrigin(0, -64);
carSprite.setScale(1, 1);
carSprite.setPosition(normalSprite.getPosition().x, normalSprite.getPosition().y);
}
Main.cpp I know it looks gross, I plan on making it look nicer later:
#include <SFML/Graphics.hpp>
#include <SFML\Graphics\Rect.hpp>
#include "player.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(750, 750), "SFML Works!");
player thePlayer;
const float gravity = .001;
int groundheight = 500;
sf::Vector2f velocity(sf::Vector2f(0, 0));
thePlayer.normal = true;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed)
{
if (thePlayer.car && event.key.code == sf::Keyboard::C)
{
thePlayer.car = false;
thePlayer.spring = false;
thePlayer.rocket = false;
thePlayer.normal = true;
break;
}
if (thePlayer.spring && event.key.code == sf::Keyboard::S)
{
thePlayer.car = false;
thePlayer.spring = false;
thePlayer.rocket = false;
thePlayer.normal = true;
break;
}
if (thePlayer.rocket && event.key.code == sf::Keyboard::R)
{
thePlayer.car = false;
thePlayer.spring = false;
thePlayer.rocket = false;
thePlayer.normal = true;
break;
}
if (event.key.code == sf::Keyboard::C)
{
thePlayer.car = true;
thePlayer.spring = false;
thePlayer.rocket = false;
thePlayer.normal = false;
break;
}
if (event.key.code == sf::Keyboard::R)
{
thePlayer.car = false;
thePlayer.spring = false;
thePlayer.rocket = true;
thePlayer.normal = false;
break;
}
if (event.key.code == sf::Keyboard::S)
{
thePlayer.car = false;
thePlayer.spring = true;
thePlayer.rocket = false;
thePlayer.normal = false;
break;
}
}
}
if (thePlayer.normal)
{
velocity.x = 0;
thePlayer.normalSprite.move(velocity.x, velocity.y);
if (thePlayer.normalSprite.getPosition().y < groundheight)
{
velocity.y += gravity;
}
else
{
thePlayer.normalSprite.setPosition(thePlayer.normalSprite.getPosition().x, groundheight);
velocity.y = 0;
}
}
if (thePlayer.car)
{
thePlayer.carSprite.move(velocity.x, velocity.y);
if (thePlayer.carSprite.getPosition().y < groundheight)
{
velocity.y += gravity;
}
else
{
thePlayer.carSprite.setPosition(thePlayer.carSprite.getPosition().x, groundheight);
velocity.y = 0;
}
}
window.clear();
if (thePlayer.normal)
{
window.draw(thePlayer.normalSprite);
}
if (thePlayer.car)
{
window.draw(thePlayer.carSprite);
}
window.display();
}
}
Thanks so much!
Before drawing the car you should adjust its position to your player position :
if (thePlayer.car)
{
thePlayer.carSprite.setPosition(thePlayer.normalSprite.getPosition());
window.draw(thePlayer.carSprite);
}
But as ractiv said, you should organize your code differently. I suggest you to learn more about c++ "good pratices" before trying to do this kind of games.
We miss the main function to know exactly what happens when the car spawns but I think that you initialize the car in the Player constructor and does not move it when the player presses 'C'.
You should have something like that :
if(event.key.code == sf::Keyboard::C) {
player.spawnCar();
}
and in your spawnCar() function :
carSprite.setPosition(normalSprite.getPosition());
EDIT
As I said in my comment, you should use getters and setters to access to your attributes. According to your current main.cpp, you should have this :
if (event.key.code == sf::Keyboard::C)
{
thePlayer.car = true;
thePlayer.spring = false;
thePlayer.rocket = false;
thePlayer.normal = false;
carSprite.setPosition(normalSprite.getPosition());
break;
}
Related
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.
I have a question to sfml.
I am relative new to C++ and sfml.
I am trying to create a Space Invaders type of game.
I currently have some problems with collision,
between the enemy's bullets and the rocket,
I'm talking about line 145. This line:
if (collide(rocket, enemy_bullets[i]))
{
window.close();
}
Can you create something like a collision box?,
because I don't want to collide with the whole rocket sprite,
I only want to collide with parts of it, e.g not the transparent parts.
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
void print(std::string string)
{
std::cout << string << std::endl;
}
sf::CircleShape create_bullet(sf::Vector2f possition, sf::Int16 offset)
{
sf::CircleShape circel;
circel.setRadius(10);
circel.setPosition(possition.x + offset, possition.y);
return circel;
}
bool collide(sf::Sprite a, sf::CircleShape b)
{
return a.getGlobalBounds().intersects(b.getGlobalBounds());
}
int main()
{
int speed;
speed = 25;
sf::RenderWindow window(sf::VideoMode(1200, 800), "Space Invaders", sf::Style::Titlebar | sf::Style::Close);
sf::Texture rocket_texture;
if (!rocket_texture.loadFromFile("data/rocket.png"))
{
print("Problem with loding file data/rocket.png");
exit(-1);
}
sf::Texture enemy_texture;
if (!enemy_texture.loadFromFile("data/enemy.png"))
{
print("Problem with loding file data/enemy.png");
exit(-1);
}
sf::Sprite rocket;
sf::Sprite enemy;
std::chrono::milliseconds couldown = std::chrono::milliseconds(0);
std::chrono::milliseconds time;
std::chrono::milliseconds enemy_couldown = std::chrono::milliseconds(0);
bool enemy_fire = false;
float bulletspeed = 0.02;
// sf::CircleShape test = create_bullet();
int changex;
rocket.setTexture(rocket_texture);
rocket.setPosition(500, 650);
rocket.scale(0.5, 0.5);
std::vector<sf::Sprite> enemy_list;
std::vector<sf::CircleShape> player_bullets;
std::vector<sf::CircleShape> enemy_bullets;
enemy.setTexture(enemy_texture);
enemy.scale(0.2, 0.2);
for (int i =0; i<8; i++)
{
enemy.setPosition(i * 150, 400);
enemy_list.push_back(enemy);
}
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
changex = 0;
switch (event.type)
{
// window closed
case sf::Event::Closed:
window.close();
break;
// key pressed
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::A)
{
if (rocket.getPosition().x >= 0 )
{
changex = changex - speed;
}
}
else if (event.key.code == sf::Keyboard::D)
{
if (rocket.getPosition().x <= 1100)
{
changex = changex + speed;
}
}
else if (event.key.code == sf::Keyboard::Space)
{
time = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
if (couldown < time - std::chrono::milliseconds(100)){
couldown = time;
player_bullets.push_back(create_bullet(rocket.getPosition(), 47));
}
}
break;
default:
break;
}
rocket.move(changex, 0);
}
window.clear();
window.draw(rocket);
//swindow.draw(test);
for (int i=0; i<player_bullets.size();i++)
{
player_bullets[i].move(0,-bulletspeed);
window.draw(player_bullets[i]);
if (player_bullets[i].getPosition().y < 0)
{
player_bullets.erase(player_bullets.begin()+i);
}
}
for (int i = 0; i < enemy_bullets.size(); i++)
{
enemy_bullets[i].move(0, bulletspeed);
window.draw(enemy_bullets[i]);
if (enemy_bullets[i].getPosition().y > 800)
{
enemy_bullets.erase(enemy_bullets.begin() + i);
}
if (collide(rocket, enemy_bullets[i]))
{
window.close();
}
}
time = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
if (enemy_couldown < time - std::chrono::milliseconds(2000))
{
enemy_couldown = time;
enemy_fire = true;
}
// Draw all Enemys
for (int i = 0; i < enemy_list.size(); i++)
{
for (int j = 0; j < player_bullets.size(); j++)
{
if (collide(enemy_list[i], player_bullets[j]))
{
enemy_list.erase(enemy_list.begin() + i);
}
}
if (enemy_fire)
{
enemy_couldown = time;
// ADD: Move enemys
enemy_bullets.push_back(create_bullet(enemy_list[i].getPosition(), 13));
}
window.draw(enemy_list[i]);
}
enemy_fire = false;
window.display();
}
return 0;
}
If you have any idea how to do that,
I would like to hear it.
Thanks, in advance
You can make a class that derives from sf::Sprite that has a sf::FloatRect for a hitbox, you will need to make a function to set the hitbox.
class Sprite : public sf::Sprite {
sf::FloatRect hitbox;
}
You can move the hitbox to the sprites location with:
getTransform().transformRect(hitbox);
I have used this in the past for hitboxes with SFML.
Edit, Here is an full example program:
#include <SFML/Graphics.hpp>
/// custom sprite class with hitbox
class HitboxSprite : public sf::Sprite {
public:
/// sets the hitbox
void setHitbox(const sf::FloatRect& hitbox) {
m_hitbox = hitbox;
}
/// gets the hitbox (use this instead of getGlobalBounds())
sf::FloatRect getGlobalHitbox() const {
return getTransform().transformRect(m_hitbox);
}
private:
sf::FloatRect m_hitbox;
};
int main() {
sf::RenderWindow window(sf::VideoMode(256, 128), "Example");
// create two sprites, player and enemy
HitboxSprite player;
player.setPosition({ 64.f, 64.f });
HitboxSprite enemy;
enemy.setPosition({ 128.f, 64.f });
enemy.setColor(sf::Color::Red);
// create sprite texture and apply to sprites
sf::Texture square_texture;
square_texture.loadFromFile("32x32square.png");
player.setTexture(square_texture);
enemy.setTexture(square_texture);
// set custom hitboxes
// (this one starts (8, 8) pixels from the top left and has a size of (16, 16)
// (this means the hitbox will be 1/2 of the square in the middle)
player.setHitbox({ 8.f, 8.f, 16.f, 16.f });
enemy.setHitbox({ 8.f, 8.f, 16.f, 16.f });
sf::Clock clock;
while (window.isOpen()) {
// process events
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
const float dt = clock.restart().asSeconds();
constexpr float player_speed = 128.f;
// move player with arrow keys
player.move({
player_speed * dt * (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) - sf::Keyboard::isKeyPressed(sf::Keyboard::Left)),
player_speed * dt * (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) - sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
});
// check for collision
const bool colliding = player.getGlobalHitbox().intersects(enemy.getGlobalHitbox());
// set background color based on collision
window.clear(colliding ? sf::Color::Green : sf::Color::Blue);
// draw sprites
window.draw(enemy);
window.draw(player);
// display
window.display();
}
return 0;
}
If you need any part explained let me know.
Here is the translucent png I made with the center part being the hitbox:
int main() {
sf::RenderWindow window;
sf::Vector2i centerWindow((sf::VideoMode::getDesktopMode().width / 2) - 445, (sf::VideoMode::getDesktopMode().height / 2) - 480);
window.create(sf::VideoMode(900, 900), "SFML Game", sf::Style::Titlebar | sf::Style::Close);
window.setPosition(centerWindow);
window.setKeyRepeatEnabled(true);
sf::Texture wallTxture;
sf::Sprite wall;
if (!wallTxture.loadFromFile("wall.png")) {
std::cerr << "Error\n";
}
wall.setTexture(wallTxture);
//Gravity Vars:
int groundHeight = 750;
bool isJumping = false;
//Movement Vars:
bool goingRight = false;
bool goingLeft = false;
//Set View Mode:
sf::View followPlayer;
followPlayer.reset(sf::FloatRect(0, 0, window.getSize().x, window.getSize().y));
Player player("newPlayer.png");
player.setPos({ 800, 800 });
sf::Vector2f position(window.getSize().x / 2, window.getSize().y / 2);
//Main Loop:
while (window.isOpen()) {
const float moveSpeed = 0.1;
sf::Event Event;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
isJumping = true;
//Handle Movement While Jumping:
if (goingLeft == true) {
player.move({ -moveSpeed, -moveSpeed });
}
else if (goingRight == true) {
player.move({ moveSpeed, -moveSpeed });
}
else {
player.move({ 0, -moveSpeed });
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
player.move({ 0, moveSpeed });
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
player.move({ -moveSpeed, 0 });
goingLeft = true;
player.flipX('l');
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
player.move({ moveSpeed, 0 });
goingRight = true;
player.flipX('r');
}
//Event Loop:
while (window.pollEvent(Event)) {
switch (Event.type) {
case sf::Event::Closed:
window.close();
case sf::Event::KeyReleased:
if (Event.key.code == sf::Keyboard::Up) {
isJumping = false;
}
else if (Event.key.code == sf::Keyboard::Left) {
goingLeft = false;
}
else if (Event.key.code == sf::Keyboard::Right) {
goingRight = false;
}
}
}
if (player.getX() > window.getSize().x) {
position.x = player.getX();
}
else {
position.x = window.getSize().x;
}
//If player is in air and not jumping:
if (player.getY() < groundHeight && isJumping == false) {
player.move({ 0, moveSpeed });
}
followPlayer.setCenter(position);
window.clear();
window.setView(followPlayer);
window.draw(wall);
player.drawTo(window);
window.display();
}
}
this is my code. What I am trying to do is create a 2D platformer sidescroller. Everything works, except when the sprite goes past a certain point it'll just disappear. This also happens when I jump and move through the air at the same time. I cannot figure out why this is happening, any help would be greatly appreciated :)
I fixed the problem by just getting rid of my flipX function, and instead just creating a new sprite facing a different direction, then changing it everytime the user is facing a new direction
In the following code a sprite can by clicked with left mouse button and then moved around freely. Then you have to hit the right button to "free" it again.
Now what is, if I want to use left button for removing the focus, instead of right button. Is this possible and how? I can't imagine, how to do it. Many thanks in advance.
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
int main()
{
sf::RenderWindow mMainWindow(sf::VideoMode(600,600), "Map", sf::Style::Close);
mMainWindow.setFramerateLimit(60);
mMainWindow.setKeyRepeatEnabled(false);
sf::Image image;
image.create(50, 50, sf::Color::Red);
sf::Texture texture;
texture.loadFromImage(image);
std::vector<sf::Sprite> EnemyVector;
sf::Sprite* focus = nullptr;
bool move = false;
while (mMainWindow.isOpen())
{
sf::Event event;
bool creating = false;
bool leftclicked = false;
bool rightclicked = false;
sf::Vector2i mousePos;
while (mMainWindow.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
mMainWindow.close();
break;
case sf::Event::KeyPressed:
creating = (event.key.code == sf::Keyboard::A);
break;
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
{
leftclicked = true;
mousePos = sf::Vector2i(event.mouseButton.x, event.mouseButton.y);
break;
}
if (event.mouseButton.button == sf::Mouse::Right)
{
rightclicked = true;
mousePos = sf::Vector2i(event.mouseButton.x, event.mouseButton.y);
break;
}
}
}
if (creating)
{
sf::Sprite sprite;
mousePos = (mousePos == sf::Vector2i(0, 0) ? sf::Mouse::getPosition(mMainWindow) : mousePos);
sprite.setTexture(texture);
sprite.setColor(sf::Color::Red);
sprite.setOrigin(static_cast<float>(sprite.getTextureRect().width) / 2, static_cast<float>(sprite.getTextureRect().height) / 2);
sprite.setPosition(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y));
focus=nullptr;
EnemyVector.push_back(sprite);
}
if (leftclicked)
{
for (auto& enemy = EnemyVector.rbegin(); enemy != EnemyVector.rend(); ++enemy)
{
if (enemy->getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y)))
{
focus = &(*enemy);
move = true;
break;
}
}
}
if(rightclicked)
{
focus = nullptr;
}
if(move)
{
if(focus!=nullptr)
{
focus->move((sf::Mouse::getPosition(mMainWindow).x - focus->getPosition().x),(sf::Mouse::getPosition(mMainWindow).y - focus->getPosition().y));
}
}
mMainWindow.clear();
for (auto& enemy = EnemyVector.rbegin(); enemy != EnemyVector.rend(); ++enemy)
{
mMainWindow.draw(*enemy);
}
mMainWindow.display();
}
return 0;
}
try this
if (leftclicked)
{
for (auto& enemy = EnemyVector.rbegin(); enemy != EnemyVector.rend(); ++enemy)
{
if (enemy->getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y)))
{
focus = &(*enemy);
move = !move;
break;
}
}
}
Trying to create a game but i've run into my first hurdle. The game launches into a blank white screen instead of showing the Red screen and i cant proceed into the loading screen and the menu. I've checked that I'm using display for each of my screens but can't figure out where i'm going wrong. I also get no errors. Below is my code
game.cpp
#include "stdafx.h"
#include "Game.h"
#include "LoadScreen.h"
#include "MainMenu.h"
void Game::Start (void)
{
Game game;
if(_gameState != Unlaunched)
return;
game._mainWindow.create(sf::VideoMode(1024,768,32),"Code Matrix");
_gameState = Game::LogoScreen;
while (!Exists())
{
GameLoop();
}
game._mainWindow.close();
}
bool Game::Exists()
{
if(_gameState == Game::Exiting)
return true;
else
return false;
}
void Game::GameLoop()
{
Game game;
sf::Event currentEvent;
while (game._mainWindow.pollEvent(currentEvent))
{
switch (_gameState)
{
case Game::MenuWindow:
{
ShowMenu();
break;
}
case Game::LogoScreen:
{
ShowLogoScreen();
break;
}
case Game::Playing:
{
sf::Event currentEvent;
while (game._mainWindow.pollEvent(currentEvent))
{
game._mainWindow.clear(sf::Color(255,0,0));
game._mainWindow.display();
if(currentEvent.type == sf::Event::Closed)
_gameState = Game::Exiting;
if(currentEvent.type == sf::Event::KeyPressed)
{
if(currentEvent.key.code == sf::Keyboard::Escape) ShowMenu();
}
}
break;
}
}
}
}
void Game::ShowLogoScreen()
{
Game game;
LoadScreen loadScreen;
loadScreen.Show(game._mainWindow);
_gameState = Game::MenuWindow;
}
void Game::ShowMenu()
{
Game game;
MainMenu mainMenu;
MainMenu::MenuOption option = mainMenu.show(game._mainWindow);
switch(option)
{
case MainMenu::Exit:
_gameState = Game::Exiting;
break;
case MainMenu::Play:
_gameState = Game::Playing;
break;
}
}
Game::GameState Game::_gameState = Unlaunched;
LoadScreen.cpp
#include "stdafx.h"
#include "LoadScreen.h"
void LoadScreen::Show(sf::RenderWindow & renderWindow)
{
sf::Texture image;
if (image.loadFromFile("images/LoadingScreen.png") !=true)
{
return;
}
sf::Sprite sprite (image);
renderWindow.draw(sprite);
renderWindow.display();
sf::Event event;
while (true)
{
while (renderWindow.pollEvent(event))
{
if(event.type == sf::Event::EventType::KeyPressed
||event.type == sf::Event::EventType::MouseButtonPressed
|| event.type == sf::Event::EventType::Closed)
{
return;
}
}
}
}
MainMenu.cpp
#include "stdafx.h"
#include "MainMenu.h"
MainMenu::MenuOption MainMenu::show(sf::RenderWindow& window)
{
//Load menu image from file
sf::Texture image;
image.loadFromFile("images/MainMenu.png");
sf::Sprite sprite(image);
//Setup clickable regions
//Play menu item coordinates
MenuItem playButton;
playButton.rect.top= 319;
playButton.rect.height = 626;
playButton.rect.left = 189;
playButton.rect.width = 329;
playButton.action = Play;
//Options menu item coordinates
MenuItem optionButton;
optionButton.rect.left = 356;
optionButton.rect.height = 596;
optionButton.rect.top = 287;
optionButton.rect.width = 483;
optionButton.action = Options;
//Exit menu item coordinates
MenuItem exitButton;
exitButton.rect.left = 554;
exitButton.rect.height = 580;
exitButton.rect.top = 318;
exitButton.rect.width = 687;
exitButton.action = Exit;
_menuItems.push_back(playButton);
_menuItems.push_back(exitButton);
window.draw(sprite);
window.display();
return GetMenuAction(window);
}
MainMenu::MenuOption MainMenu::HandleClick(int x, int y)
{
std::list<MenuItem>::iterator it;
for ( it = _menuItems.begin(); it != _menuItems.end(); it++)
{
sf::Rect<int> menuItemRect = (*it).rect;
if( menuItemRect.height > y
&& menuItemRect.top < y
&& menuItemRect.left < x
&& menuItemRect.width > x)
{
return (*it).action;
}
}
return null;
}
MainMenu::MenuOption MainMenu::GetMenuAction(sf::RenderWindow& window)
{
sf::Event menuEvent;
while(true)
{
while(window.pollEvent(menuEvent))
{
if(menuEvent.type == sf::Event::MouseButtonPressed)
{
return HandleClick(menuEvent.mouseButton.x,menuEvent.mouseButton.y);
}
if(menuEvent.type == sf::Event::Closed)
{
return Exit;
}
}
}
}
void Game::ShowLogoScreen()
{
Game game; // <- this creates a NEW game. You want to use your already created game.
LoadScreen loadScreen;
loadScreen.Show(game._mainWindow);
_gameState = Game::MenuWindow;
}
You create a new game local to the logo screen. That one probably does not even own a window. You should reference your existing game variable.