'how can i draw a sprite by left clicking?

i've tried to make a project, but i can't draw a sprite as i want. I mean that everything works when i just draw a sprite, but it stop working when i am trying to draw the sprite by clicking left mouse button. There's code i tried:

if(zdarzenie.type == Event::MouseButtonPressed && zdarzenie.mouseButton.button == Mouse::Left)
{
pocisk.setPosition(10, 10);
oknoAplikacji.draw(pocisk);
}

Btw, I am writing in Polish as if it would change something. And yes, i have everything good besides that. (and i am using 2.4.1 version of SFML)



Solution 1:[1]

I don't know what you are doing now because you didn't provide enough of your code and I actually don't understand your if statement but, it can just be :

if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
    sprite.setPosition(sf::Mouse::getPosition());
    renderTarget.draw(sprite);
}

By the way I strongly suggest that you do not use the draw function here but organize your code to have a draw method called in a render loop, because depending on where your code is in your program, the sprite could be drawn for only one frame and then erased since it's not updated.

Solution 2:[2]

From what I understand in your code in Polish, you have the right code to do what you want, but the problem comes from the fact that you draw the sprite only once.

The draw method is called every frame and it will erase everything on screen and then redraw them. Doing it only once, like in your code, will only draw it a single time then delete it the very next frame.

At that point multiple solution can be used. If its a GameObject clicking can activate the object to then draw it or a simple bool could be used has a switch in your draw to make it appear.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Psolyvem
Solution 2 Bodeje