So I'm new to both c++ and sfml and I want to make some simple project like the color of the box to change color when I click it or the position.
this is my code so far,
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Main.hpp>
#include <iostream>
#include <string>
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(512, 512), "My window", sf::Style::Fullscreen | sf::Style::Default);
std::string x = "Blue";
sf::Texture background;
sf::Sprite Background;
Background.setTexture(background);
Background.scale(3, 3.0);
sf::RectangleShape box (sf::Vector2f(100.0f, 100.0f));
box.setFillColor(sf::Color::Red);
box.setPosition(100, 100);
sf::FloatRect collision = box.getGlobalBounds();
sf::Vector2i point = sf::Mouse::getPosition(window);
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))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
/*case sf::Event::TextEntered:
if (event.text.unicode < 128)
{
printf("%c", event.text.unicode);
}*/
}
}
/*if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
player.move(0, -2);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
player.move(0, 2);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
player.move(-2,0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
player.move(2, 0);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
sf::Vector2i mousePos = sf::Mouse::getPosition(window);
player.setPosition(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y));
}*/
auto mouse_pos = sf::Mouse::getPosition(window); // Mouse position relative to the window
auto translated_pos = window.mapPixelToCoords(mouse_pos); // Mouse position translated into world coordinates
if (box.getGlobalBounds().contains(translated_pos)) // Rectangle-contains-point check
{
box.setFillColor(sf::Color::Green);
}
window.clear(sf::Color::Blue);
//window.draw(Background);
window.draw(box);
window.display();
}
return 0;
}
I took the code from tutorials and other post on the forum but the color changes as soon as the cursor approaches the box.
How can I make a the box change color when I click it?