SFML community forums

Bindings - other languages => DotNet => Topic started by: oddikaro on July 08, 2021, 07:20:30 pm

Title: Dealing with events
Post by: oddikaro on July 08, 2021, 07:20:30 pm
Hi all,

I would like to move shape objects within the window. Events in SFML .NET are substantially different than using C++, e.g.:


...
        window.Closed += OnWindowClosed;
...

        private static void OnWindowClosed(object sender, EventArgs e)
        {
            (sender as RenderWindow).Close();
        }
 

That is possible since the sender object is the window itself, so you can do something with the window if you want. However, if you create a shape and you want to modify some properties when the keyboard is pressed, I don't see a clear way of doing it.

Of course, if the shape is accessible (e.g., "MyShape" as a property in the class), you can make changes in any arbitrary function:
        private static void OnKeyPressed(object sender, KeyEventArgs e)
        {
            if (e.Code == Keyboard.Key.Escape)
            {
                (sender as RenderWindow).Close();
            }
            if (e.Code == Keyboard.Key.Left)
            {
                MyShape.Position = new Vector2f(MyShape.Position.X - 10, MyShape.Position.Y);
            }
        }
 

However, I don't like to access external variables from an event function, I would prefer to pass them as a parameter. Or you may have another suggestion.
Title: Re: Dealing with events
Post by: eXpl0it3r on July 09, 2021, 08:58:28 pm
On the other hand, the beauty of C# events is that you can assign as many handlers as you want.
With that in mind it's perfectly reasonable to have local handle functions where ever you need them and += them to the event.