Tag Archives: XNA

Simulating Fixed and Line Joints in Farseer Physics Engine 3.5

Recently there was a new release of the excellent Farseer Physics Engine. Since my game is still in very early stage and I am still mucking around with samples and tweaking the settings I decided to upgrade since performance improvements is one of the things changed. Not that the old version was slow, but since I am inexperienced in game programming and quite likely doing some things in a non optimal way I though I could use those extra CPU cycles.

However version 3.5 is not backwards compatible and among other things it no longer includes fixed joints like FixedRevoluteJoint etc. and I have been using those in my proof of concept. As it turns out it is quite easy to achieve the things I used to use fixed joints for.

Firstly, credit where credit is due – a lot of my code is based on Farseer Samples and this post by Roy Triesscheijn.

Anyway I was testing various paddles as explained in the code that can be downloaded from the blog post mentioned above.

Here is how everything looks in action:

In Farseer 3.3, the code for the motorised paddle would look like this:

Body motorPaddle = CreateMotorPaddle();

var j = JointFactory.CreateFixedRevoluteJoint
        (
                World,
                motorPaddle,
                new Vector2(0.0f, 0.0f),
                new Vector2(-14.0f, 10.0f)
                );

// set motor speed
j.MotorSpeed = MathHelper.Pi;

// set torque and enable motor
j.MotorTorque = 100; 
j.MotorEnabled = true;
j.MaxMotorTorque = 100;

In version 3.5 you can achieve the same thing by the code below. Note the use of another static body to act as an axle:

Body motorPaddle = CreateMotorPaddle();
Body motorPaddleAxle = BodyFactory.CreateCircle(World, 0.1f, 1f);

var j = JointFactory.CreateRevoluteJoint
    (
        World,
        motorPaddle,
        motorPaddleAxle,
        new Vector2(0.0f, 0.0f),
        new Vector2(-14.0f, 10.0f)
        );

// set speed and torque
j.MotorSpeed = MathHelper.Pi;
j.MotorImpulse = 100; 
j.MotorEnabled = true;
j.MaxMotorTorque = 100;

The code for free swinging paddle is more or less the same, except that the motor is not enabled and would look like the code below:

Body simplePaddle = CreateSimplePaddle();
Body simplePaddleAxle = BodyFactory.CreateCircle(World, 0.1f, 1f);

JointFactory.CreateRevoluteJoint
    (
        World,
        simplePaddle,
        simplePaddleAxle,
        new Vector2(0.0f, -1.4f),
        new Vector2(25.0f, 10.0f)
        );

The trampoline was implemented using LineJoint in Farseer 3.3. That code looked like this:

Body trampolineAnchor1 = CreateTrampolineAnchor1();
Body trampolineAnchor2 = CreateTrampolineAnchor2();
Body trampolinePaddle = CreateTrampolinePaddle();

var spring1 = JointFactory.CreateLineJoint
        (
                trampolineAnchor1,
                trampolinePaddle,
                new Vector2(12.0f, 11.0f),
                Vector2.UnitY
                );

spring1.CollideConnected = true;
spring1.Frequency = 3.0f;
spring1.DampingRatio = 0.05f;

World.AddJoint(spring1);

var spring2 = JointFactory.CreateLineJoint
        (
                trampolineAnchor2,
                trampolinePaddle,
                new Vector2(16.0f, 11.0f),
                Vector2.UnitY
                );

spring2.CollideConnected = true;
spring2.Frequency = 3.0f;
spring2.DampingRatio = 0.05f;

World.AddJoint(spring2);

LineJoint is gone in Farseer 3.5, but there we can use WheelJoint instead, like in the code below. A wheel join allows rotation and suspension like movement along a specified axis.

Body trampolineAnchor1 = CreateTrampolineAnchor1();
Body trampolineAnchor2 = CreateTrampolineAnchor2();
Body trampolinePaddle = CreateTrampolinePaddle();

var spring1 = JointFactory.CreateWheelJoint
    (
        World,
        trampolinePaddle,
        trampolineAnchor1,
        Vector2.UnitY
        );

spring1.CollideConnected = false;
spring1.Frequency = 3.0f;
spring1.DampingRatio = 0.05f;

World.AddJoint(spring1);

var spring2 = JointFactory.CreateWheelJoint
    (
        World,
        trampolinePaddle,
        trampolineAnchor2,
        Vector2.UnitY
        );

spring2.CollideConnected = false;
spring2.Frequency = 3.0f;
spring2.DampingRatio = 0.05f;

World.AddJoint(spring2);

That is it!

Farseer Physics Engine

Recently, I have started to get ready to create a retro inspired 2D platformer game and as part of this I was looking for a physics engine suitable for use with MonoGame.

It seems that Farseer is the most popular library for these kind of things out there and there are samples included in MonoGame Samples project on GitHub. Those samples are targetting OS X, but adapting them for iOS is not difficult:

  • I had to re-generate some of content files to get them to load (it seems that spritefonts are a bit quirky on iOS) which is easy to do with MonoGame Content Project. But you better do so on a Windows 7 machine as it requires some parts of XNA Game Studio that require a bit of hacking to get them to work on a Windows 8 machine. I prefer to leave my Windows Phone development environment as it is so I used a Windows 7 virtual machine.
  • And you have to touch enable everything which was a breeze as the samples are beautifully written and easy to read.
    • The end result is this:

      Very nice! and all the collision detections and bouncing of the car and so forth is managed by Farseer! All you have to do is define a World, define its gravity, add some bodies to the world and specify their weight, define any relationships between objects such as how the tyres of the car are related to car chassis and so on. Very neatly done!

Playing with Kinect

Kiandra IT recently organised a hackaton titled Touch and Gestures. As you might guess it ended up being mostly about gesture enabling different things. Touch has been around for so long that most of us perceive it as something normal. While gestures are not new either there are some new exciting developments in that area going on, I am talking about https://www.leapmotion.com/. There is a lot of potential there. And of course there is the well known Microsoft Kinect.

There were four teams and the guys worked on a windows management system using Leap Motion, Kinect enabled story wall, a Leap Motion enabled web dashboard and of course the thing I am going to write about here :)

I teamed up with a colleague to Kinect enable my 3D Snooker game.  Here is a quick video of what we came up with (this is a slightly tweaked version, but the core remains the same).

So how does one go about using Kinect in a MonoGame?

Initializing Kinect is easy:

            KinectSensor _sensor = KinectSensor.KinectSensors.First();
            _sensor.SkeletonStream.Enable(); // Enable skeletal tracking
            _sensor.Start();

First we get a reference to Kinect sensor, then enable tracking of data we are interested in and start the whole thing. In our case we opted to enable SkeletonStream as we wanted to track position of our hands.

Next we need to handle Kinect events. We opted to use RX extensions and observe the event stream that way. At this point my colleague took over as he is a bit of a gun when it comes to using RX extensions. Here is the code:

            var skeletonData = new Skeleton[_sensor.SkeletonStream.FrameSkeletonArrayLength];
            var events = Observable.FromEventPattern<SkeletonFrameReadyEventArgs>(_sensor, "SkeletonFrameReady").Publish();
            
            var skeletons = events
                .Select(e =>
                    {
                        using (var skeletonFrame = e.EventArgs.OpenSkeletonFrame())
                        // Open the Skeleton frame
                        {
                            if (skeletonFrame != null)
                            // check that a frame is available
                            {
                                skeletonFrame.CopySkeletonDataTo(skeletonData);
                                return skeletonData.LastOrDefault(x => x.TrackingState == SkeletonTrackingState.Tracked);
                            }
                            return null;
                        }
                    })
                .Where(x => x != null);

            var handVectors = skeletons.Select(GetHandsVector);

            // calculate angles and speed

            events.Connect();

In a nutshell, we subscribed to SkeletonFrameReady event and whenever we had a skeleton frame in Tracked status used that data to calculate the vector between left and right hand.
The vector was calculates simply by substracting right hand’s position from left hand’s position, like so:

        private static Vector3 GetHandsVector(Skeleton sk)
        {
            var rightPosition = sk.Joints.First(x => x.JointType == JointType.HandRight).Position;
            var leftPosition = sk.Joints.First(x => x.JointType == JointType.HandLeft).Position;
            return ToVector3(leftPosition) - ToVector3(rightPosition);
        }

        private static Vector3 ToVector3(SkeletonPoint leftPosition)
        {
            return new Vector3(leftPosition.X, leftPosition.Y, leftPosition.Z);
        }

As you move your hands the vector changes and we used it’s angle relative to X and Y axis to rotate the cue. Simple! :)

We also wanted to use gesture to trigger a shot and the idea was to track the speed as you move hands together, then, when hands are close enough to each other we would take that speed and trigger the shot. This is something that still doesn’t work quite well. We were dealing with two problems here:

  • How to stop the cue from rotating when you want to make a shot and
  • Getting an accurate speed reading.

After the hackaton (actually today) I solved the first problem by cheating a little bit. If you looked at the video above you probably noticed that I was holding a wireless mouse. I decided to use left mouse click to lock rotation in. Right mouse button click is used to switch between moving the cue ball (when allowed) and rotating the cue. I’ve been told that Kinect for Windows allows you to track palm movements, so when you make a fist that is treated like a click. I am using Kinect for XBox 360 here and this one does not support such funky things. So the trick with a wireless mouse is here to stay until I get my hands on Kinect for Windows.

The problem with speed remains though. So how do we calculate the speed?


            // calculate distance between hands
            Distances = handVectors.Select(x => x.Length());

            // determine if there was a shot played
            const float NEAR_ZERO = 0.3f;
            var distanceTime = Distances.TimeInterval();
            var speeds = distanceTime.Zip(distanceTime.Skip(1), (a, b) => Math.Abs((a.Value - b.Value) / (a.Interval.TotalMilliseconds - b.Interval.TotalMilliseconds)));
            Shoots = speeds.WhereOther(Distances, x => Math.Abs(x) < NEAR_ZERO);

First we track the distance between hands and the time intervals at which frames are coming in. The speed is the distance traveled divided by the time it took to travel this far. Just as your physics teacher told you 😉

We only report speeds to the game engine once hands are close enough to each other. Like I said, there are still some issues and this method is somewhat unreliable. But I am yet to have any new ideas.

This is it. Hope you found it interesting :)

Using gestures in MonoGame (and XNA)

I was trying to use this bit of code yesterday, but it didn’t work:

        protected override void Update(GameTime gameTime)
        {
            while (TouchPanel.IsGestureAvailable)
            {
                var gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.FreeDrag)
                {
                    _cue.Rotate(gesture.Delta, GraphicsDevice.Viewport.Bounds);
                }
            }

            base.Update(gameTime);
        }

Why? Because I forgot to enable gestures! This line was all that was missing:

            TouchPanel.EnabledGestures = GestureType.FreeDrag;

EnabledGestures is a flag property so you can enable multiple types of gestures by using bitwise or, like, for example:

 TouchPanel.EnabledGestures = GestureType.FreeDrag | GestureType.Tap;

In my rotate method I simply translate the delta into something more useful, which in my cases are degrees:

        public void Rotate(Vector2 delta, Rectangle viewPortBounds)
        {
            var degreesAroundYAxis = (delta.X / viewPortBounds.Width) * 360;
            var degreesAroundXAxis = (delta.Y / viewPortBounds.Height) * 90;
            Rotation += new Vector3(MathHelper.ToRadians(degreesAroundXAxis), MathHelper.ToRadians(degreesAroundYAxis), 0.0f);

            if (MathHelper.ToDegrees(Rotation.X) < 5.0f)
            {
                Rotation = new Vector3(MathHelper.ToRadians(5.0f), Rotation.Y, Rotation.Z);
            }
        }

Starting with MonoGame

I love coding little apps for my phone and (hopefully soon) tablet. The project I am working on now is porting a simple Snooker game I wrote using DirectX and C++ nearly a decade ago over to Windows 8 and Windows Phone devices.

My initial plan was to just copy my C++ code to a Direct3D project, tweak a few things and see it run. An overly optimistic goal, given my rusty C++ skills and the fact that DirectX API has evolved a lot since DirectX 8. So I started looking for alternatives that would get me to my goal quicker (I like to keep my hobby project short). If XNA had support on Windows 8 and Windows Phone 8 devices I would go with that one, but since they are not I started looking at MonoGame which is an open source implementation of XNA API. And it is awesome.

To get started you need to get MonoGame source code from GitHub by cloning the repository. The source contains VS2012 templates, copy these over to your templates folder and you are ready to start coding with MonoGame. For more details on how to do this follow instructions at bob’s blog. But you will need to (or can) do certain things differently!

First, MonoGame project has evolved a bit since and now you will have three VS2012 templates in there:

  • Game is the one you want to use if you are writing a game using MonoGame only,
  • XamlGame is a combination of MonoGame and XAML and
  • WindowsPhone is obvious

Secondly, before you can load your mesh models into your game you need to convert them into XNB file format, but at the moment there are no Content Importers in XNA. So you will need to use project templates that come with XNA Game Studio in order to convert the models to XNB format. There were some issues with installing XNA on Windows 8 in the past (see Aaron Stebner’s WebLog) but if you install Windows Phone 8 SDK it installs without a problem and you can use XNA Content project from VS2012. Then create a “Content” folder within your MonoGame project and copy XNB files in there (mark them as Content in properties and make sure they are always copied to output directory). I believe you could tweak the location by changing the line below in your Game class:

Content.RootDirectory = "Content";

This should have you ready and going. As for myself, I have this after one day:

Snook