Hello, I am new to these forums, and it was only recently that I registered. For a while now I have continuously encountered this aggravating problem. I search for hours to find a solution, but all to no avail. So I came here to ask if anyone could help.
My problem is with changing the sprite's color to red, then having it wait a half of a second, and then changing back. I wanted this to occur when a key is pressed. The problem is that I have to hold down the key for it to occur. It won't occur otherwise. If i just change "event.key.code" to "isKeyPressed" it doesn't help me at all.
I use sfml clock to do this, but I am not sure what i am doing wrong.
The key in question that I press is the space bar.
Here is the code:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <SFML\My Additions to SFML\sfml.h> // this file is just for linkig sfml, so if it is already linked, don't worry about it
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
int sprite_on_screen;
sf::RenderWindow window(sf::VideoMode(1700, 900), "SFML RPG test");
float x;
float y;
int rectleft = 300;
int recttop = 0;
int rectwidth = 300;
int rectheight = 300;
sf::Event event;
sf::Texture texture;
sf::IntRect rectSourceSprite(rectleft, recttop, rectwidth, rectheight);
sf::Sprite sprite(texture,rectSourceSprite);
sf::Clock clock1;
int color1 = sprite.getColor().toInteger();
void Clock0_Function(){
if (clock1.getElapsedTime().asSeconds() > 0.5f){
sprite.setColor(sf::Color::Red);} // increase and decrease
if (clock1.getElapsedTime().asSeconds() > 1.0f){
sprite.setColor(sf::Color(sf::Color(color1)));
clock1.restart();}
sprite.setTextureRect(rectSourceSprite);}
void Define_Texture(){
texture.loadFromFile("Stickman sprite.png");}
void Define_Sprite_Position(){
sprite.setPosition(1050, 500);}
void Redefine_Sprite_Position(){
sprite.setPosition(950, 300);}
void Change_Sprite(){
switch (event.type){
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if((event.key.code == sf::Keyboard::Space))
Clock0_Function();
break;}}
int main(){
window.setVerticalSyncEnabled(true);
Define_Sprite_Position();
Define_Texture();
while(window.isOpen())
{
while (window.pollEvent(event)){
Change_Sprite();
if (event.type == sf::Event::EventType::Closed){
window.close();}
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::F5))){
window.close();}
}
window.clear();
window.draw(sprite);
window.display();
}
return 0;}