Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Dealing with events  (Read 9429 times)

0 Members and 1 Guest are viewing this topic.

oddikaro

  • Newbie
  • *
  • Posts: 5
    • View Profile
Dealing with events
« 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.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11044
    • View Profile
    • development blog
    • Email
Re: Dealing with events
« Reply #1 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything