How to draw an object onto sfml window when a function is called? - c++

I have a character sprite moving across the screen and when I press 'a' I want the program to draw the sword sprite onto the screen and make the sword go away when I am not pressing 'a'. Currently I have an attack function that sets a showweapon boolean as true, and a if statement that is supposed to draw the weapon onto the screen but nothing happens. Is there a better way to do this?
main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Character.h"
#include "Projectile.h"
#include "Weapon.h"
using namespace std;
bool scroll = false;
Character player("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/Player.png");
Weapon woodsword("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/WoodSword.png");
bool showweapon;
int main() {
// insert code here...
int windowWidth = 5000;
int windowHeight = 5000;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight ), "Awesome Game" );
sf::Texture dungeon;
dungeon.loadFromFile("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/DungeonBack.png");
sf::Sprite backround;
backround.setTexture(dungeon);
while (window.isOpen()){
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event)){
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
player.left();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
player.right();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
player.forward();
}
if (sf:: Keyboard::isKeyPressed(sf::Keyboard::Down)){
player.backward();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
{
player.Highspeed();
}
else{
player.Lowspeed();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
woodsword.attack();
}
window.clear(sf::Color(255, 255, 255));
window.draw(backround);
if(showweapon == true){
window.draw(woodsword.getSprite());
window.display();
cout << "Hello";
}
window.draw(player.getSprite());
window.display();
window.setFramerateLimit(70);
}
}
I am also not receiving the "hello" message
weapon.h
class Weapon : Character{
bool showweapon;
public:
sf::Texture texture;
//Constructor
Weapon(string wep)
: Character(wep){
texture.loadFromFile(wep);
showweapon = false;
}
sf::Sprite getSprite() {
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(0, 0, 100, 100));
sprite.setPosition(x_pos, y_pos);
return sprite;
}
//Methods
void attack();
};
void Weapon::attack(){
showweapon = true;
}
If you need to see anything else let me know. Thanks for any help!

I changed the if statement to : if (woodsword.showweapon == true) and I also made a sheath method in the weapon class that sets showweapon false so the sword goes away when I don't press 'a'. Thanks for everyones help.

Related

button in cpp sfml lib don't respond to my mouse input

I have to make Quarto game as a GUI program so firstly I wanted to make buttons in menu, but I don't know why it don't fill color when my mouse is at the button.
Code:
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include<bits/stdc++.h>
using namespace std;
using namespace sf;
class button{
public:
bool isClicked=false;
int Yposition;
int Xposition;
bool isMouseOn=false;
};
int main(){
//Defining variables
Vector2i mouseWindowPosition;
//rendering window "window"
RenderWindow window(VideoMode(800,600), "Quarto game - menu", Style::Default);
window.display();
//setting vsync
window.setVerticalSyncEnabled(true);
//loading textures
Texture backgroundTexture;
backgroundTexture.loadFromFile("Resources/background.png");
//making sprites
Sprite backgroundSprite;
backgroundSprite.setTexture(backgroundTexture);
backgroundSprite.setPosition(0,0);
//making buttons and their colors
RectangleShape playButton(Vector2f(200.f,50.f));
playButton.setFillColor(Color(128,128,128));
playButton.setOutlineThickness(5.f);
playButton.setOutlineColor(Color(100,100,100));
button play;
//setting position of buttons
play.Xposition=70;
play.Yposition=200;
//game loop
while(window.isOpen()){
Event event;
playButton.setFillColor(Color(128,128,128));
play.isMouseOn=false;
while(window.pollEvent(event)){
if(event.type==Event::Closed){
window.close();
}
}
//Getting mouse position
mouseWindowPosition=Mouse::getPosition(window);
if(mouseWindowPosition.x<=play.Xposition && mouseWindowPosition.y<=play.Yposition && mouseWindowPosition.x>=play.Xposition+200 && mouseWindowPosition.y>=play.Yposition+50){
play.isMouseOn=true;
}
//Drawing to screen
window.clear();
window.draw(backgroundSprite);
if(play.isClicked==false){
playButton.setPosition(Vector2f(play.Xposition, play.Yposition));
window.draw(playButton);
}
if(play.isMouseOn==true){
playButton.setFillColor(Color(128,128,128));
}
window.display();
}
}
Is there any better way to make buttons in sfml?
The immediate reason why the button doesn't fill is your if the statement has the signs reversed for checking the box. Using this if statement instead should work:
//Getting mouse position
mouseWindowPosition=Mouse::getPosition(window);
if (mouseWindowPosition.x>=play.Xposition && mouseWindowPosition.y>=play.Yposition &&
mouseWindowPosition.x<=play.Xposition+200 && mouseWindowPosition.y<=play.Yposition+50){
//your code here
}
If you are not already aware, the x and y values are arranged like a table where positive y goes down instead of a cartesian coordinate system where positive y is up.
The other problem is the color you are updating your fill with is the same color of the fill, so changing that color will get you your desired fill.
Also, logic wise you should swap the statement
if (play.isMouseOn == true)
{
}
with the statement
if (play.isClicked == false)
{
playButton.setPosition(Vector2f(play.Xposition, play.Yposition));
window.draw(playButton);
window.display();
}
Here is a working code that changes the fill from grey to red when you hover above it:
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
using namespace std;
using namespace sf;
class button
{
public:
bool isClicked = false;
int Yposition;
int Xposition;
bool isMouseOn = false;
};
int main()
{
//Defining variables
Vector2i mouseWindowPosition;
//rendering window "window"
RenderWindow window(VideoMode(800, 600), "Quarto game - menu", Style::Default);
window.display();
//setting vsync
window.setVerticalSyncEnabled(true);
//loading textures
Texture backgroundTexture;
backgroundTexture.loadFromFile("Resources/background.png");
//making sprites
Sprite backgroundSprite;
backgroundSprite.setTexture(backgroundTexture);
backgroundSprite.setPosition(0, 0);
//making buttons and their colors
RectangleShape playButton(Vector2f(200.f, 50.f));
playButton.setFillColor(Color(100, 100, 100));
playButton.setOutlineThickness(5.f);
playButton.setOutlineColor(Color(100, 100, 100));
button play;
//setting position of buttons
play.Xposition = 70;
play.Yposition = 200;
//game loop
while (window.isOpen())
{
Event event;
playButton.setFillColor(Color(128, 128, 128));
play.isMouseOn = false;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
}
//Getting mouse position
mouseWindowPosition = Mouse::getPosition(window);
if (mouseWindowPosition.x >= play.Xposition && mouseWindowPosition.y >= play.Yposition && mouseWindowPosition.x <= play.Xposition + 200 && mouseWindowPosition.y <= play.Yposition + 50)
{
play.isMouseOn = true;
}
//Drawing to screen
window.clear();
window.draw(backgroundSprite);
if (play.isMouseOn == true)
{
playButton.setFillColor(Color(128, 0, 0));
}
if (play.isClicked == false)
{
playButton.setPosition(Vector2f(play.Xposition, play.Yposition));
window.draw(playButton);
window.display();
}
}
}

C++ and SFML, no instance of the overloaded function "sf::RenderWindow.draw()" matches the argument list

I am currently trying to make a simple pong game with SFML in C++. I consistently get the error in the main file.
#include <iostream>
#include "Ball.h"
Ball b;
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here...
window.draw(b);
// end the current frame
window.display();
}
return 0;
}
This is the ball.h file:
#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
double x, y;
int Radius;
void Render(int Rad, sf::Color BallColour) {
sf::CircleShape shape(Rad);
// set the shape color to green
shape.setFillColor(BallColour);
}
};
I am unsure as to why the error occurs. Any help would be appreciated.
You had not call function of render, you just wrote window.draw(b), and programm dont know what do you mean. In Ball.h you should write:
#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
double x, y;
int Radius;
void Render(int Rad, RenderWindow& window) {
sf::CircleShape shape(Rad);
// set the shape color to green
shape.setFillColor(sf::Color::Green);
shape.setPosition(600, 300);//SETTING POSITION OF THE BALL
window.draw(shape);//if you know what is reference on variable, you will understand what is it
}
};
And in your main.cpp you shhould call your function Render:
#include <iostream>
#include "Ball.h"
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");
Ball b; //I advice you to create object of class in main function
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
window.clear(sf::Color::Black);
b.Render(10, window);// give the function reference on window
// end the current frame
window.display();
}
return 0;
}
sf::RenderWindow::draw requires an implementation of sf::Drawable. You can either pass sf::CircleShape (it's a sf::Drawable) directly or implement sf::Drawable and delegate the call.
class Ball : public sf::Drawable {
public:
double x, y;
int Radius;
void draw(sf::RenderTarget& target, sf::RenderStates states) const override {
sf::CircleShape shape(Radius);
shape.setFillColor(BallColour);
shape.draw(target, states);
}
};

Falling sand simulation collision detection C++ and SFML

I could really use some help. I am trying to make a falling sand simulation and have some basic code down, but I can't figure how to do collision detection. Here is my code so far:
//SFML Include
#include <SFML/Graphics.hpp>
//Include Vectors
#include <vector>
//Main Loop
int main()
{
//Window Init
sf::RenderWindow window(sf::VideoMode(720, 480, 32), "Yip Yip Physics", sf::Style::Default);
//Global Envoirmental Variables
static float gravity = 0.25;
static float frict = 3;
//Particle Structures
struct Particle
{
//Shape
sf::RectangleShape rect;
//Cell Position
sf::Vector2f cell_pos;
//Vel and frict
float slide_vel = 3;
float grv_vel = 0;
//Init Particle (size, color and origin)
void init()
{
rect.setSize(sf::Vector2f(3, 3));
rect.setFillColor(sf::Color::Green);
rect.setOrigin(rect.getSize());
}
};
//Particle Setup
std::vector<Particle> particles;
//Window Loop
while (window.isOpen())
{
//Update
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left))
{
//Make and Position Particle
Particle part;
part.rect.setPosition(sf::Vector2f(sf::Mouse::getPosition(window)));
//Initalize the Particle and add to vector
part.init();
particles.push_back(part);
}
//Pixel Update
for (auto& p : particles)
{
//Draw in window
window.draw(p.rect);
}
//Display
window.display();
//Event Variable
sf::Event event;
//Window Event System
while (window.pollEvent(event))
{
//Close Window
if (event.type == sf::Event::Closed)
{
window.close();
}
}
//Window Clear
window.clear(sf::Color::Black);
}
//Return 0
return 0;
}
The code works in making the particles, putting them in a vector and drawing them to the screen, but I don't know where to go for collision. I don't know where to look and would really appreciate help on it or direction on where to find it. I have heard a bit about cellular automata but have no idea how to do it or if it's the best option.

ะก++ sfml how to draw shapes with help mouse

I want create simulation on C++. I want: when I press the mouse button, a circle should appear in the coordinates. I want use class or void or struct. And call it is class when i click on mouse (I already made this condition).
Here is an example to draw circle on click button at mouse position:
#include <SFML/Graphics.hpp>
#include <vector>
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "WINDOW_TITLE");
window.setFramerateLimit(50);
std::vector<sf::Shape*> shapes;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
{
window.close();
return 0;
}
case sf::Event::MouseButtonPressed:
{
sf::CircleShape *shape = new sf::CircleShape(50);
shape->setPosition(event.mouseButton.x,event.mouseButton.y);
shape->setFillColor(sf::Color(100, 250, 50));
shapes.push_back(shape);
}
}
}
window.clear();
for(auto it=shapes.begin();it!=shapes.end();it++)
{
window.draw(**it);
}
window.display();
}
return 0;
}

SFML - Creating a cursor and printing input?

So I've downloaded SFML and so far love it. I've run into a roadblock and am trying to figure out how to implement a blinking cursor into the code below. I also need to figure out how to print a single char (when the user presses a key on the keyboard) onto the window. Here's some code I've used ever since I've downloaded SFML 2.0:
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <iostream>
int main() {
sf::RenderWindow wnd(sf::VideoMode(650, 300), "SFML Console");
sf::Vector2u myVector(650, 300);
wnd.setSize(myVector);
sf::Font myFont;
myFont.loadFromFile("theFont.ttf");
sf::Color myClr;
myClr.r = 0;
myClr.g = 203;
myClr.b = 0;
sf::String myStr = "Hello world!";
std::char myCursor = '_';
sf::Text myTxt;
myTxt.setColor(myClr);
myTxt.setString(myStr);
myTxt.setFont(myFont);
myTxt.setCharacterSize(12);
myTxt.setStyle(sf::Text::Regular);
myTxt.setPosition(0, 0);
std::int myCounter = 0;
while(wnd.isOpen()) {
sf::Event myEvent;
while (wnd.pollEvent(myEvent)) {
if (myEvent.type == sf::Event::Closed) {
wnd.close();
}
if (myEvent.type == sf::Event::KeyPressed) {
if (myEvent.key.code == sf::Keyboard::Escape) {
wnd.close();
}
}
wnd.clear();
wnd.draw(myTxt);
myCounter++;
std::if (myCounter >= 1000) {
myCounter = 0;
}
std::if (myCounter < 1000) {
myTxt.setString("Hello world!_");
}
wnd.display();
}
}
}
Use sf::Clock (doc).
Declare your clock along with your other variables before your main loop, this also starts the clock automatically. In your loop, check for the time elapsed and reset the clock if it exceeds what you want. Example :
sf::Clock myClock; // starts the clock
bool showCursor = false;
// ...
wnd.draw(myTxt);
if(clock.getElapsedTime() >= sf::milliseconds(500))
{
clock.restart();
showCursor = !showCursor;
if(showCursor)
myTxt.setString("Hello World!_");
else
myTxt.setString("Hello World!");
}
// ...
This should give you a cursor blinking by 0.5 second.
By the way, why are you using std::if() instead of a plain if that is included in the language ?