MouseHandler Events and Delegates c# -
i have been looking @ events , delegates on last few days , decided attempt make mousehandler class using both of these.
basically have problem mouse clicks not registering , positions x , y axis coming 0, not registering mean displaying in output console through console.writeline(). have been researching while have had no luck wondering if of guys point me in right direction appreciated.
thank in advance.
mousehandler.cs
class mousehandler { public delegate void mouseeventhandler(object source, mouseeventhandlerargs public event mouseeventhandler mouseleftclick; public event mouseeventhandler mouserightclick; public event mouseeventhandler mousemoved; public mousestate mousestate = mouse.getstate(); protected virtual void onmouseleftclick(mousestate m) { mousestate = m; if(mouseleftclick != null) { mouseleftclick(this, new mouseeventhandlerargs() { mousebuttonpress = m }); } } protected virtual void onmousemoved(mousestate m) { if (mousemoved != null) { mousemoved(this, new mouseeventhandlerargs(){mousebuttonpress = m }); console.writeline(mousestate.position.x); } } public void update(gametime gt) { onmouseleftclick(mousestate); onmousemoved(mousestate); } }
mouseeventhandlerargs
class mouseeventhandlerargs : eventargs { public mousestate mousebuttonpress { get; set; } }
mousetest
class mousetest { public void onmouseleftclick(object source, mouseeventhandlerargs e) { console.writeline("mouse left click" + e.mousebuttonpress.leftbutton); } public void onmousemoved(object source, mouseeventhandlerargs e) { console.writeline("you moved mouse x " + e.mousebuttonpress.position.x + " y pos " + e.mousebuttonpress.position.y ); } }
game1 within update method:
mousehandler.mouseleftclick += mousetest.onmouseleftclick; mousehandler.mousemoved += mousetest.onmousemoved; //mousehandler.update(gametime);
a couple of problems:
1) looks you're triggering event before checking if button clicked or mouse moved.
2) you're getting mouse state once when class instantiated. you'll need call mouse.getstate()
in update()
method.
// new class fields private buttonstate _previousbuttonstate = buttonstate.released; private int _previousmousex; private int _previousmousey; // new update() method public void update(gametime gt) { mousestate mousestate = mouse.getstate(); // check if left button clicked (pressed now, not last update()) if (mousestate.leftbutton == buttonstate.pressed && _previousbuttonstate != buttonstate.pressed) onmouseleftclick(mousestate); _previousbuttonstate = mousestate.leftbutton; // see if mouse has moved since last update() if (mousestate.x != _previousmousex || mousestate.y != _previousmousey) { onmousemoved(mousestate); _previousmousex = mousestate.x; _previousmousey = mousestate.y; } }
Comments
Post a Comment