SFML Mouse event

#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
void helper(sf::RenderWindow& window)
{
	while(window.isOpen())
	{
		sf::Event fEvent;
		int previous_x = fEvent.mouseMove.x;

		while(window.pollEvent(fEvent))
		{
			if(fEvent.type == sf::Event::Closed)
				window.close();
			if(fEvent.type == sf::Event::KeyPressed)
			{
				if(fEvent.key.code == sf::Keyboard::Left){
					cout << "keyboard left" << endl;
				}
				if(fEvent.key.code == sf::Keyboard::Right){
					cout << "keyboard right" << endl;
				}
				if(fEvent.key.code == sf::Keyboard::Space){
					cout << "keyboard shoot" << endl;
				}

			}

			if(sf::Event::MouseMoved  && (previous_x - fEvent.mouseMove.x)>1){

					cout << "mouse left" << endl;

			}
			else if(sf::Event::MouseMoved  && (fEvent.mouseMove.x - previous_x)>1)
			{
				cout << "mouse right" << endl;

			}
			else if(sf::Event::MouseButtonPressed && fEvent.mouseButton.button == sf::Mouse::Left)
			{
				cout << "mouse shoot" << endl;

			}
			previous_x = fEvent.mouseMove.x;

		}
		window.display();
	}
}
int main()
{
	sf::RenderWindow window;
	window.create(sf::VideoMode(200, 200), "Testing");

	helper(window);

}
Last edited on
1
2
3
4
5
6
7
8
			if(fEvent.type == sf::Event::KeyPressed)
			{
...
			}

			else
			{
				if(sf::Event::MouseMoved  && (previous_x - fEvent.mouseMove.x)>1){


You have your mouse handling code in an else statement. That means that for every single event type other than keydown (ie: window close, key up, window resize, etc, etc), you will be running your mouse handling code.

You have to look specifically for mouse events.. and only have your mouse handling code when a mouse event happens.
thanks for the reply. but omitting else won't help. i think i'm not calculating previous mouse position and current mouse position right. any suggestions for that please?
Errr.... are you just deleting the else? Or are you replacing it with a check for mouse events?

You need to be doing the latter.


EDIT:

To clarify further:

1
2
3
4
if(fEvent.type == sf::Event::KeyPressed)  // <- this is how you check if an event is a Key Pressed event

if(fEvent.type == sf::Event::MouseMoved) // <- this is how you check to see if an event
   // is a mouse moved event 


You are never doing that 2nd check. Instead you are doing this:

 
if(sf::Event::MouseMoved)


Which is always going to be true because that value is nonzero.
Last edited on
i have edited the code. i have deleted the else. but i think sf::Event::MouseMoved checks the mouse event.
but i think sf::Event::MouseMoved checks the mouse event.


Only if you check fEvent.type to make sure its value equals sf::Event::MouseMoved
Last edited on
omg what a stupid mistake by me. thank you so much. i couldnt find this error for hours
Topic archived. No new replies allowed.