Creating Custom GameObjects

Most of the logic and interactive elements of a game are implemented through the creation of custom GameObject classes. GameObjects form the heart-and-soul of your game by defining everything from player characters and enemies, to background elements such as trees or furniture, to control elements which do not appear in game but drive game functionality (think enemy spawners, activation points, or state machines).

A basic game object implementation for a player character might look like:

Imports GdiGaming

Public Class MyHeroCharacter
    Inherits GameObject

    Private _TargetPosition As Vector2

    Public Sub New()
        Name = "Hero"
        HasCollision = True
        ProcessInput = True
        CollisionRadius = 14
    End Sub

    Protected Overrides Sub OnInput(e As GdiGaming.GameEngineEventArgs)
        'set the target position we are trying to move to based
        'on keyboard input plus current position
    End Sub

    Protected Overrides Sub OnLoad(e As GdiGaming.GameEngineEventArgs)
        'load sprites and any other assets needed
    End Sub

    Protected Overrides Sub OnUpdate(e As GdiGaming.GameEngineEventArgs)
        'if target position is not the current position, validate the
        'target position and if valid update the current position
    End Sub
End Class

A player character object will likely implement custom code for OnInput (to handle user input) and OnUpdate to perform the player logic. The comments above indicate logic that would allow our player hero to move around. Any visible GameObject will also provide code for OnLoad which can load the required sprites (see Sprites and Objects for more info) and other assets.

The OnUpdate() game logic method is called on all game objects regardless of the container they are assigned to within a Scene (see Creating Custom GameScenes for more info on containers) so long as the object is enabled. Every GameObject offers an Enabled property which can be set to False to suspend updates (and all other activity) for that object.

The OnInput() method is only called on an object whose ProcessInput property is set to True. Typically the player character and perhaps certain HUD elements are the only objects which process input. The majority of objects will execute their logic in the OnUpdate method.

The OnLoad() method is called by the engine whenever the game object is accessed and its IsLoaded property is False. Typically the OnLoad method is used to add sprites to an object and set up any other visual requirements. This should be considered a one-time setup for a game object, however, the object could reset its internal _IsLoaded field to False in order to force the engine to reload the object the next time it is used.

For examples of actual GameObject implementations, see the Chopper-Game Example.

Last edited Dec 29, 2011 at 8:42 PM by ReedKimble, version 1


No comments yet.