Creating Window (SFML / C#)

In this post, we are going to create a window using SFML.Net and also explained the lines of the code example below.

Firstly, We have to import SFML libraries which are Graphics and Window. This window will be sized as 640px width and 480px height. Also, we need to specify the title of the window. I just declared the constant variables code below.

We are going to use struct VideoMode as built-in and class RenderWindow as built-in to create a window. You can take a look at the source of these structs via lmb + ctrl

We called SetVerticalSyncEnabled and set as true. In summary, we activated vertical synchronization to be synchronized with the vertical frequency of the monitor. You can learn more from this link[] why we use that. 

Well, this wasn't actually familiar to me. Maybe some of the readers of the blog know already what is this. This is just to handle the close event as defined in RenderWindow if the user closes the window. If you don't know what is this you should read on callbacks, event/delegates for .NET. I recommend this article[] to read, and also callbacks are should be known because it's used for most design patterns which the blog author never mentioned (but I will) on this blog until this post. 

Let's dive in. window.Closed is actually an event with a defined built-in delegate EventHandler. If interaction with close button then close the window with window.Close(). In DispatchEvents function, the events which defined are be controlled in for each frame. We used lambda expression instead of the standard method. I think this makes the code readable and concise.

In this line, we created a while loop and gave the condition for if the window is open then run it. There is a bool property called IsOpen as a parameter from window object which typed RenderWindow. So this loop is actually our game loop.

In the game loop, we have to call DispatchEvents method to handle events. 

After that, we need to clear the window with some color. I used Blue Color from struct Color as built-in in SFML.Graphics.

Finally, we can display the window. 

using System;
using SFML.Graphics;
using SFML.Window;

namespace shmup
    class Program
        const int WIDTH = 640;
        const int HEIGHT = 480;
        const string TITLE = "SHMUP";
        static void Main(string[] args)
            VideoMode mode = new VideoMode(WIDTH, HEIGHT);
            RenderWindow window = new RenderWindow(mode, TITLE);

            window.Closed += (sender, args) => window.Close();

            while (window.IsOpen)

No comments:

Post a Comment