Tuesday, March 8, 2016

A Functional ECS

I recently changed my distro from Mint Cinnamon to ElementaryOS. My research had reached the conclusion that the issues I was having with Unity3D were due to old kernal. I'm happy to report that it's a success - I can now access the Unity Store. And with the latest 5.3.3 version, some breaking changes have been resolved. All of this allows me to get back to FSharp.

And so, I've finished up my very basic port of Entitas to FSharp. While converting the demo game, ShmupWarz, I started wondering if my systems could just be functions. And why not use FSharp's built in pattern matching instead of calling a Match api? Could I juse express my ECS directly in FSharp?

So, for example, I could write the movement system like this:

let MovementSystem (delta:float32) entity =

    match entity.Velocity, entity.Position with

    | Some(velocity), Some(position) ->
        let x = position.X + velocity.X * delta
        let y = position.Y + velocity.Y * delta
        { entity with Position = Vector2(float32 x, float32 y)}

    | _ -> entity

Where the oop version looks like this:

type MovementSystem(world:World) =

    let group = world.GetGroup(Matcher.AllOf(Matcher.Position, Matcher.Velocity))

    interface IExecuteSystem with
        member this.Execute() =

            let delta = Time.deltaTime/100.0f

            for e in (group.GetEntities()) do
                e.position.x <- e.position.x + (e.velocity.x * delta)
                e.position.y <- e.position.y + (e.velocity.y * delta)
                e.position.z <- e.position.z + (e.velocity.z * delta)



While reading this post https://bruinbrown.wordpress.com/2013/10/06/making-a-platformer-in-f-with-monogame/ I noticed that the author was using a pattern very similar to en ECS. So I played with it a bit, tweaked the naming convention, and got it working.

I went ahead and created a full game for a poc. You can see it at https://github.com/darkoverlordofdata/mono-fsharp-shmupwarz

Performance seems just as good, although I'm comparing MonoGame to Unity3D. So my next step is to try to integrate this technique with Unity.

No comments:

Post a Comment