Sunday, December 13, 2015

Using FSharp with Unity

Getting the FSharp binaries to work with Unity is pretty well covered here: Tutorial: Using F# with Unity3D. I was able to get up and running with Unity 5.2.2f1 on Linux Mint 17 and MonoDevelop 5.10.

I started working through the Unity Angry Birds tutorial, and ran into some problems with the mouse. Really, though, it turned out to be an error between chair and keyboard while trying to re-implement the csharp tutorial code in fsharp.

At first attempt, this line looked like it should be changed from this

    Vector2 catapultToMouse = mouseWorldPoint - catapult.position;

to this:

    let catapultToMouse = mouseWorldPoint - catapult.position

The problem with is that now, 'catapultToMouse' becomes a Vector3. The caused problems latter on when 'catapultToMouse.sqrMagnitude' had an unexpected value. I fixed this with a helper function that converts a Vector3 to a Vector2:

    let catapultToMouse = Vec32(mouseWorldPoint - catapult.position)


The other issue I ran into was my code was not deetecting a null value for a unity component. It turns out to be a known issue F# null test fails to detect null values

After these two issues were resolved, I was able to get the demo working. And finally, to enable touch support on Android, I added this code to the end of the Update method:

        if Input.touchCount > 0 then
            match Input.GetTouch(0).phase with
            | TouchPhase.Began -> this.OnMouseDown()
            | TouchPhase.Ended -> this.OnMouseUp()
            | TouchPhase.Canceled -> this.OnMouseUp()
            | _ -> ()


The entire project is located here

No comments:

Post a Comment