Converting a GameMaker: Studio project to MonoGame (Part 3)

In Part 2 we wrote the Room class including the loader. Of course, I made a mistake in the code I hadn’t tested.
This line:

should be

I thought it checked the current namespace by default, clearly I was wrong.

Today, we’re going to write the code to draw and update objects, and we’ll start to implement the player object.

Object abstract class
Ok, let’s open Object.cs.

The using directives we’ll need are:

and we want the class to look like this:

Note that this is an abstract class. All actual objects (i.e. player, baddie and minime) will derive from this, implementing their own Create and Step methods, just as in GM:S.

Object needs some members:

Most of these are directly taken from GM:S, and need no explanation. I’ve also added sprite_origin_x and sprite_width etc. This is because, in GM:S these are properties of the sprite, but I’ll not bothering to implement a full sprite class, we’re just using Texture2D.

These are all marked as public. This is the GM:S way of doing things, and will be necessary later on. Normally I would be tempted to write a lot of these as protected.

We need to add the declarations for the abstract methods objects will implement:

These are protected, so that they cannot be called any old time.

Then we can add a constructor, which will call Create straight away:

Note that we’ll have to call this constructor explicitly as base(int,int) from derived classes.

Then our drawing method:

The SourceRect property does exactly the same as we had for the Tile struct, and the Draw method uses it to draw on screen, with various other variables.
Notice that I have labelled Draw as virtual: this is so that derived classes can override it if they wish. We will do this for the minime object, as the GM:S project does for its draw.

Finally, we need an update function. This is a public function which will be called once per frame, which will call Step and then animate the sprite:

Hopefully if you think about it for a second you will see that this implements image_speed as we want it (i.e. being the number of frames of animation per frame of the game).

At this point, the code should compile, but nothing will be changed.

Updating and drawing instances
Open up Room.cs. First let’s get the instances drawn, so find the Draw function, and just before spriteBatch.End(); add:

Pretty simple, right?

We will also need a new Update method, as follows: