Game Architecture - c#

I have a question about a XNA game I'm making, but it is also a generic question for future games. I'm making a Pong game and I don't know exactly what to update where, so I'll explain better what I mean. I have a class Game, Paddle and Ball and, for example, I want to verify the collisions between the ball with the screen limits or the paddles, but I come across 2 approaches to do this:
Higher Level Approach - Make paddle and ball properties public and on the Game.Update check for collisions?
Lower Level Approach- I supply every info I need (the screen limits and paddles info) to the ball class (by parameter, or in a Common public static class) and on the Ball.Update I check for collisions?
I guess my question in a more generic way is:
Does an object need to know how to update and draw itself, even having dependencies from higher levels that somehow are supplied to them?
or
Is better to process it at higher levels in Game.Update or Game.Draw or using Managers to simplify code?
I think this is a game logic model question that applies to every game. I don't know if I made my question clear, if not, feel free to ask.

The difficult part of answering your question is that you're asking both: "what should I do now, for Pong" and "what should I do later, on some generic game".
To make Pong you don't even need Ball and Paddle classes, because they're basically just positions. Just stick something like this in your Game class:
Vector2 ballPosition, ballVelocity;
float leftPaddlePosition, rightPaddlePosition;
Then just update and draw them in whatever order suits you in your Game's Update and Draw functions. Easy!
But, say you want to create multiple balls, and balls have many properties (position, velocity, rotation, colour, etc): You might want to make a Ball class or struct that you can instance (same goes for the paddles). You could even move some functions into that class where they are self-contained (a Draw function is a good example).
But keep the design concept the same - all of the object-to-object interaction handling (ie: the gameplay) happens in your Game class.
This is all just fine if you have two or three different gameplay elements (or classes).
However let's postulate a more complicated game. Let's take the basic pong game, add some pinball elements like mutli-ball and player-controlled flippers. Let's add some elements from Snake, say we have an AI-controlled "snake" as well as some pickup objects that either the balls or the snake can hit. And for good measure let's say the paddles can also shoot lasers like in Space Invaders and the laser bolts do different things depending on what they hit.
Golly that is a huge mess of interaction! How are we going to cope with it? We can't put it all in Game!
Simple! We make an interface (or an abstract class or a virtual class) that each "thing" (or "actor") in our game world will derive from. Here is an example:
interface IActor
{
void LoadContent(ContentManager content);
void UnloadContent();
void Think(float seconds);
void UpdatePhysics(float seconds);
void Draw(SpriteBatch spriteBatch);
void Touched(IActor by);
Vector2 Position { get; }
Rectangle BoundingBox { get; }
}
(This is only an example. There is not "one true actor interface" that will work for every game, you will need to design your own. This is why I don't like DrawableGameComponent.)
Having a common interface allows Game to just talk about Actors - instead of needing to know about every single type in your game. It is just left to do the things common to every type - collision detection, drawing, updating, loading, unloading, etc.
Once you're in the actor, you can start worrying about specific types of actor. For example, this might be a method in Paddle:
void Touched(IActor by)
{
if(by is Ball)
((Ball)by).BounceOff(this.BoundingBox);
if(by is Snake)
((Snake)by).Kill();
}
Now, I like to make the Ball bounced by the Paddle, but it is really a matter of taste. You could do it the other way around.
In the end you should be able to stick all your actors in a big list that you can simply iterate through in Game.
In practice you might end up having multiple lists of actors of different types for performance or code simplicity reasons. This is ok - but in general try to stick to the principle of Game only knowing about generic actors.
Actors also may want to query what other actors exist for various reasons. So give each actor a reference to Game, and make the list of actors public on Game (there's no need to be super-strict about public/private when you're writing gameplay code and it's your own internal code.)
Now, you could even go a step further and have multiple interfaces. For example: one for rendering, one for scripting and AI, one for physics, etc. Then have multiple implementations that can be composed into objects.
This is described in detail in this article. And I've got a simple example in this answer. This is an appropriate next step if you start finding that your single actor interface is starting to turn into more of a "tree" of abstract classes.

You could also opt to start thinking about how different components of the game need to talk to each other.
Ball and Paddle, both are objects in the game and in this case, Renderable, Movable objects.
The Paddle has the following criteria
It can only move up and down
The paddle is fixed to one side of the screen, or to the bottom
The Paddle might be controlled by the user (1 vs Computer or 1 vs 1)
The paddle can be rendered
The paddle can only be moved to the bottom or the top of the screen, it cannot pass it's boundaries
The ball has the following criteria
It cannot leave the boundaries of the screen
It can be rendered
Depending on where it gets hit on the paddle, you can control it indirectly (Some simple physics)
If it goes behind the paddle the round is finished
When the game is started, the ball is generally attached to the Paddle of the person who lost.
Identifying the common criteria you can extract an interface
public interface IRenderableGameObject
{
Vector3 Position { get; set; }
Color Color { get; set; }
float Speed { get; set; }
float Angle { get; set; }
}
You also have some GamePhysics
public interface IPhysics
{
bool HasHitBoundaries(Window window, Ball ball);
bool HasHit(Paddle paddle, Ball ball);
float CalculateNewAngle(Paddle paddleThatWasHit, Ball ball);
}
Then there is some game logic
public interface IGameLogic
{
bool HasLostRound(...);
bool HasLostGame(...);
}
This is not all the logic, but it should give you an idea of what to look for, because you are building a set of Libraries and functions that you can use to determine what is going to happen and what can happen and how you need to act when those things happen.
Also, looking at this you can refine and refactor this so that it's a better design.
Know your domain and write your ideas down.
Failing to plan is planning to fail

You could see your ball and paddle as a component of your game, and XNA gives you the base class GameComponent that has an Update(GameTime gameTime) method you may override to do the logic. Additionally, there is also the DrawableGameComponent class, which comes with its own Draw method to override. Every GameComponent class has also a Game property which holds the game object that created them. There you may add some Services that your component can use to obtain information by itself.
Which approach you want to make, either have a "master" object that handles every interaction, or provide the information to the components and have them react themselves, is entirely up to you. The latter method is preferred in larger project. Also, that would be the object-oriented way to handle things, to give every entity its own Update and Draw methods.

I agree with what Andrew said. I am just learning XNA as well and in my classes, for example your ball class. I'd have an Update(gametime) method and a Draw() method in it at the least. Usually an Initialize(), Load() as well. Then from the main game class I will call those methods from their respective cousins. This was before I learned about GameComponent. Here is a good article about if you should use that. http://www.nuclex.org/blog/gamedev/100-to-gamecomponent-or-not-to-gamecomponent

Related

How can I realise different actions (e.g. change scenery, interact with npc, pick up items) using the input system of Unity?

I am using the (new) input system of Unity and have the problem to realise an interaction with different objects. I am still quite new to Unity and hope to find some help.
I have created an event (OnInteract) that listens to whether e has been pressed.
Next I created an object with a collider into which my player can run. Whenever the player meets a certain collider, something should happen. In my case I want to change the scene. However, on my initial scene there are two doors that the player can open by pressing e. I have given both doors the same layer name because they are both exits.
Basically, it works that I can only press e when I hit this particular collider. However, I don't know how to do it instead of performing two different actions. Maybe there is a way to give the objects a script that I can trigger via the PlayerMovement script. Without taking it into the player.
this is my script that works so far:
void OnInteract(InputValue value)
{
if (myBoxCollider.IsTouchingLayers(LayerMask.GetMask("Entrance")))
{
Debug.Log("interact with the door");
}
}
or is there perhaps a way to listen to the "tag" instead of the layer?
I have also come across interfaces, but have not really understood how these help me. Or how I have to use them here to make them work.
In the end you're going to have to check some kind of tag, layer, or reference a component. it's just your preference. To make it a little simpler you can shoot a raycast in the direction you are looking to check for objects instead of having colliders. But in the end it's doing the same thing.
I don't really use interfaces as I'm pretty new myself but from what I can tell they are generally used for organization and global accessibility in similar objects, like doors lol.

Pass diverse parameters to a delegate

I want many GameObjects on the scene to have the Y position "animated" programmatically. I have a class, let's call it "TheGameObject", which doesn't inherit from MonoBehaviour and as such can't have the Update() function that I need to achieve the Y movement of the GameObjects.
I decided to try using a delegate but then a problem came up: I can pass only one Transform to the delegate.
Here's the code for the delegate in a static class, let's call it "staticClass", that derives from MonoBehaviour:
public delegate void UpdatingEventHandler(Transform t);
public static event UpdatingEventHandler Updating;
void Update() {
if(Updating != null)
Updating(/*Transform that should be passed*/);
}
And this is the code in the "TheGameObject" class:
public GameObject gameObject { get; set; }
private void spawn() {
GameObject go = new GameObject();
staticClass.Updating += animateYpos(go.transform);
}
void animateYpos(Transform t) {
//modify t.position.y
}
Is there a way to pass each respective Transform to the delegate in order to call Updating() in the static class Update() and have all the GameObjects to move respectively?
The problem isn't the type of the parameter that is passed but which Transform is passed so that each different Transform will have its own Y position modified.
This is sort of totally wrong, Cress!
It's very common for experienced developers to not really understand that Unity
is not object oriented, and has utterly no connection - at all - to concepts like inheritance.
(Sure, the programming language currently used for writing components in Unity, happens to be OO, but that's largely irrelevant.)
Good news though, the solution is incredibly simple.
All you do in Unity is write behaviors that do what you want.
Essay about it ... https://stackoverflow.com/a/37243035/294884
Try to get this concept: say you have a "robot attack device" in your game.
So, the only thing in Unity scenes is GameObjects. (There is nothing else - at all.)
Your "robot attack device" would have these behaviors. ("Behaviours" meaning components attached to it. Componantes are MonoBehavior.)
"robot attack device"
• animate Z position
• shoot every ten seconds
• respond to bashes with sound effect
and so on.
Whereas, your "kawaii flower" might have these behaviors
"kawaii flower fixed NPC"
• shoot every 5 seconds
• respond to bashes with sound effect
• rainbow animation
In this case you're asking how to write a "animate Y" behavior.
It's very easy, first note that everything - everything - you do in Unity you do with an extension, so it will be like
public static void ForceY( this Transform tt, float goY )
{
Vector3 p = tt.position;
p.y = goY;
tt.position = p;
}
Quick tutorial on extensions: https://stackoverflow.com/a/35629303/294884
And then regarding the trivial component (all components are trivial) to animate Y, it's just something like
public class AlwaysMoveOnYTowards:MonoBehaviour
{
[System.NonSerialized] public float targetY;
void Update()
{
float nextY = .. lerp, or whatever, towards targetY;
transform.ForceY(nexyT);
}
}
Note that, of course, you just turn that component on and off as needed. So if the thing is asleep or whatever in your game
thatThing.GetComponent().enabled = false;
and later true when you want that behavior again.
Recall, all you're doing is making a model for each thing in yoru game (LaraCroft, dinosaur, kawaiiFlower, bullet .. whatever).
(Recall there are two ways to use models in Unity, either use Unity's prefab system (which some like, some don't) or just have the model sitting offscreen and then Instantiate or use as needs be.)
{Note that a recent confusion in Unity (to choose one) is: until some years ago you had to write your own pooling for things that you had a few of. Those days are long gone, never do pooling now. Just Instantiate. A huge problem with Unity is totally out-of-date example code sitting around.}
BTW here's the same sort of ForceY in the case of the UI system
public static void ForceYness(this RectTransform rt, float newY)
{
Vector2 ap = rt.anchoredPosition;
ap.y = newY;
rt.anchoredPosition = ap;
}
Finally if you just want to animate something on Y to somewhere one time, you should get in to the amazing
Tweeng
which is the crack cocaine of game engineering:
https://stackoverflow.com/a/37228628/294884
A huge problem with Unity is folks often don't realize how simple it is to make games. (There are many classic examples of this: you get 1000s of questions asking how to make a (totally trivial) timer in Unity, where the OP has tied themselves in knots using coroutines. Of course, you simply use Invoke or InvokeRepeating 99% of the time for timers in Unity. Timers are one of the most basic parts of a game engine: of course, obviously unity through in a trivial way to do it.)
Here's a "folder" (actually just a pointless empty game object, with these models sitting under it) holding some models in a scene for a game.
those are some of the enemies in the game. As an engineer I just popped them in there, the game "designer" would come along and set the qualities (so, the potato is fast, the turnip is actually an unkillable boss, the flying head connects to google maps or whatever).
Same deal, this is from the "folder" (aside, if you use an empty game object as a, well, folder to just hold shit, it's often referred to as a "folder" - it's no less a game object) with some "peeps" ("player projectiles"). Again these are the very models of these things to be used in the game. So obviously these would just be sitting offscreen, as you do with games. Look, here they are, literally just sitting around an "-10" or something outside of the camera frustrum (a good place to remember a Unity "camera" is nothing more than ............. a GameObject with certain components (which Unity already wrote for our convenience) attached.)
(Again: in many cases you may prefer to use prefabs. Unity offers both approaches: prefabs, or "just sitting offscreen". Personally I suggest there is a lot to be said for "just sitting offscreen" at first, as it makes you engineer proper states and so on; you'll inherently have to have a "just waiting" state and so on, which is highly important. I strongly encourage you, at first, to just 'sit your models around offscreen', don't use prefabs at first. Anyway that's another issue.)
Here then are indeed some of those peeps ...
Thank God, I was born an engineer, not a wanker "game designer" so someone else comes along and sets that sort of thing as they see fit. (And of course, indeed adds the profoundly important (from a player point of view) Components such as, you know, "the renderer", sound effects, and the like.
Note, Cress: you may notice above: because "life's like that" in the naming there (it's purely a naming issue, not a deep one) we very un-sensibly went against just what I describe here. So, notice I have a component that should be named, say, "Killableness" or perhaps just "projectileness" or indeed just "power" or "speed". Just because life's like that, I rather unsensibly named it "missile" or "projectile" rather than indeed "flight" or "attackPower". You can see this is very very bad because when I reuse the component "attackPower" (stupidly named here "missile") in the next project, which involves say robotic diggers or something rather than missiles, everyone will scream at me "Dude why is our attack power component, attached to our robotic spiders, called 'missile' instead of 'attack power', WTF?" I'm sure you see what I mean.
Note too, there's a great example there of, while Unity and GameObject have no connection at all to computer science or programming, it's totally normal - if confusing - that in writing components you have to be a master of OO since (as it happens) the current language used by Unity does indeed happen to be an OO language (but do bear in mind they could change to using Lisp or something at any time, and it wouldn't fundamentally affect Unity. As an experienced programmer you will instantly see that (for the components discussed here) I have something like a base class "Flightyness" and then there are subclasses like "ParabolaLikeFlightyness" "StraightlineFlightyness" "BirdFlightyness" "NonColliderBasedFlightyness" "CrowdNetworkDrivenFlightyness" "AIFlightyness" and so on; you can see each have the "general" settings (for Steve the game designer to adjust) and more specific settings (again for Steve to adjust). Some random code fragments that will make perfect sense to you...
public class Enemy:BaseFrite
{
public tk2dSpriteAnimator animMain;
public string usualAnimName;
[System.NonSerialized] public Enemies boss;
[Header("For this particular enemy class...")]
public float typeSpeedFactor;
public int typeStrength;
public int value;
public class Missile:Projectile
{
[Header("For the missile in particular...")]
public float splashMeasuredInEnemyHeight;
public int damageSplashMode;
Note the use of [Header ... one of the most important things in Unity! :)
Note how good the "Header" thing works, especially when you chain down through derives. It's nothing but pleasure working on a big project where everyone works like that, making super-tidy, super-clear Inspector panels for your models sitting offscreen. It's a case of "Unity got it really right". Wait until you get to the things they fucked up! :O
Please conside what Joe said but for passing multiple paramaters to a delegate you can use this iirc :
public delegate void DoStuffToTransform(params Transform[] transform);

Understand Single Responsibility Principle of SOLID design

I'm currently trying to learn the SOLID design principles along with behavior driven development, but am having quite the hard time getting my head around the Single Responsibility Principle. I've tried to find a good tutorial for c# that uses test driven development, but haven't been able to find anything worthwhile in that vein. Anyway, after spending a few days reading about it, I decided the best way to learn is by experience, so I started creating a small app using those principles best I can.
It's a simple bowling score calculator. I figured the best way to go about it was to work from the simplest part up, so I started at the ball (or throw) level. Right now I have created tests and an interface and class for dealing with ball(throw) scores, which makes sure they aren't invalid, ie. <10 or >0. After implementing this I realized that the ball class is basically just a nullable integer, so maybe I don't even need it... but for now it's there.
Following the ball, I decided the next logical thing to add was a frame interface and class. This is where I have gotten stuck. Here is where I'm at:
namespace BowlingCalc.Frames
{
public interface IFrame : BowlingCalc.Generic.ICheckValid
{
void AddThrow(int? score);
int? GetThrow(int throw_number);
}
}
namespace BowlingCalc.Frames
{
public class Frame : IFrame
{
private List<Balls.IBall> balls;
private Balls.IBall ball;
private int frame_number;
public Frame(Balls.IBall ball, int frame_number)
{
this.ball = ball;
this.frame_number = frame_number;
balls = new List<Balls.IBall>();
check_valid();
}
public void AddThrow(int? score)
{
var current_ball = ball;
current_ball.Score = score;
balls.Add(current_ball);
}
public int? GetThrow(int throw_number)
{
return balls[throw_number].Score;
}
public void check_valid()
{
if (frame_number < 0 || frame_number > 10)
{
throw (new Exception("InvalidFrameNumberException"));
}
}
}
}
The frame uses my previously implemented ball class through dependency injection to add ball scores to the frame. It also implements a way to return the score for any given ball in the frame.
What I want to do, and where I'm stuck, is I want to add a way to make sure the frame score is valid. (For the moment just the simple case of frames 1-9, where the combined score of both balls must be 10 or less. I will move on to the much more complicated frame 10 case later.)
The problem is I have no idea how to implement this in a SOLID way. I was thinking of adding the logic into the class, but that seems to go against the single responsibility principle. Then I thought to add it as a separate interface/class and then call that class on each frame when its score updates. I also thought of creating a separate interface, IValidator or something like that, and implementing that in the Frame class. Unfortunately, I have no idea which, if any, of these is the best/SOLID way of doing things.
So, what would be a good, SOLID way to implement a method that validates the score of a frame?
Note: Any critique of my code is very welcome. I am very excited learn to create better code, and happy to receive any help given.
When I think SRP, I tend to put the emphasis on the Responsibility aspect. The name of the class, in turn, should ideally describe its Responsibility. For some classes this is about what the class is supposed to 'be' (a Frame could be a good example if it lacks behavior and merely represents state), but when you have a behavioral responsibility, the name is about what the class is supposed to 'do'.
Computing scores by itself is a fairly small responsibility, so let's consider something slightly larger and more naturally decomposable. Here is one possible breakdown of a bowling game with simple responsibilities and with suitably paranoid encapsulation (we're all friends here, but nobody wants anybody to cheat by mistake.)
//My job is to keep score; I don't interpret the scores
public interface IScoreKeeper : IScoreReporter
{
void SetScore(int bowlerIndex, int frameIndex, int throwIndex, int score);
}
//My job is to report scores to those who want to know the score, but shouldn't be allowed to change it
public interface IScoreReporter
{
int? GetScore(int bowlerIndex, int frameIndex, int throwIndex);
}
//My job is to play the game when told that it's my turn
public interface IBowler
{
//I'm given access to the ScoreReporter at some point, so I can use that to strategize
//(more realisically, to either gloat or despair as applicable)
//Throw one ball in the lane, however I choose to do so
void Bowl(IBowlingLane lane);
}
//My job is to keep track of the pins and provide score feedback when they are knocked down
//I can be reset to allow bowling to continue
public interface IBowlingLane
{
int? GetLastScore();
void ResetLane();
}
//My job is to coordinate a game of bowling with multiple players
//I tell the Bowlers to Bowl, retrieve scores from the BowlingLane and keep
//the scores with the ScoreKeeper.
public interface IBowlingGameCoordinator
{
//In reality, I would probably have other service dependencies, like a way to send feedback to a monitor
//Basically anything that gets too complicated and can be encapsulated, I offload to some other service to deal with it
//I'm lazy, so all I want to do is tell everybody else what to do.
void PlayGame(IScoreKeeper gameScore, IEnumerable<IBowler> bowlers, IBowlingLane lane);
}
Note that if you wanted to use this model to simply compute scores (without playing a real game), you can have a stub Bowler (who does nothing) and a MockBowlingLane, who produces a series of score values. The BowlingGameCoordinator takes care of the current bowler, frame and throw, so the scores get accumulated.
What is the purpose of ICheckValid interface? Do you call check_valid elsewhere? In my opinion, since the frame_number seems to be in fact a read-only property of a Frame, why it would be wrong to verify its consistency right in the constructor without any additional interfaces for that? (Constructors are supposed to produce consistent objects and are thus free to validate incoming parameters however they like.)
However, rather than to ask how to properly validate this field, it might be better to ask why indeed you need the frame_number property in the Frame? It seems like this is an index of this item in some array - you may just use the index, why store it in the Frame? You may want to write some if/else logic later, such as:
if (frame_number == 10) {
// some rules
} else {
// other rules
}
However, this is unlikely a SOLID approach as you would probably end up writing this if/else statements in many parts of the Frame. Rather, you may create a base class FrameBase, define much of the logics there plus some abstract methods to be implemented in OrdinaryFrame and TenthFrame, where you would define different rules. This would enable you to avoid frame_number altogether -- you would just create nine OrdinaryFrames and one TenthFrame.
As for critique: your code seems to abstract balls and frames, but ignores 'throws', or 'rolls' for some reason. Consider a need to add trajectory information of each roll, you would need to change the IFrame interface, adding something like void SetThrowTrajectory(int throwNumber, IThrowTrajectory trajectory). However, if you abstract throws away in an e.g. IBallRoll, the trajectory-related functionality would easily fit there (as well as some Boolean computed properties, e.g. IsStrike, IsSpare).

XNA AI: Managing Enemies on Screen

I have two classes, Human and Monster.
both have a Property called MoveBehavior
Human has HumanMoveBehavior, and Monster has MonsterMoveBehavior
I want the HumanMoveBehavior to move AWAY from Monsters, and MonsterMoveBehavior to move TOWARD Humans.
The problem I'm having is where should I put my code to move?
In the Human/Monster class?
Using this approach, I had a Move() Method, which takes a List of all entities in game, decides whether it's a Monster or Human using a method called GetListOfOpponents(List allsprites) and then runs GetNearestOpponent(List opponents);
But this looks really messy.
Should I have a SpriteController that decides where the Sprites move? I'm unsure where I need to put this code :(
Thanks!
You could think of a AIManager that just says:
foreach(GameObject go in m_myObjects) // m_myObjects is a list of all objects that require updating
{
go.Update(); // standard GameObject function
}
After that, each class should take care of its own piece of code. So updating works in the class itself.
So Human says:
// just a class which is a gameObject and also has moving behaviour
// do the same with monster
public class Human : GameObject, IMoveBehaviour
{
public override Update()
{
GoMove();
}
public void GoMove()
{
// human specific logic here
}
}
// This interface describes that some movement
// will happen with the implementing class
public interface IMoveBehaviour
{
void GoMove();
}
With using an interface, you can make the specific language part of the class and you don't have need to ALSO create some class that will handle that for you. Of course it is possible. But in real life, the human/monster is the one that is moving, not some object he is carrying.
UPDATE
Answer to the comment. Because there is an AIManager, or even a complete GameObjectManager would be nice to maintain all GameObjects, you could ask the AIManager for the placed where you could not go.
Because pathfinding is most of the time done by use of some navigation mesh or a specified grid, the GameObjectManager can return the specific Grid with all navigable points on it. You should for certain not define all positions in every monster. Because most of the time, the monster does not exactly know where everyone is (in real life). So knowing where not to go is indeed good, but knowing where everyone is, will give your AI too much advantage as well.
So think of returning a grid with the points where to go and where not to, instead of maintaining such things inside the monster/human. Always check where you should leave what, by thinking about what would be the thing in real life.
The way Valve handled this for entities in Half Life 2, is one of the better ways, I think. Instead of giving each AI its own separate Move methods and calling those, it simply called the Think() method and let the entity decide what it needed to do.
I'd go with what Marnix says and implement an AIManager that loops through each active AI in the game world, calling the Think() method of each. I would not recommended interfacing your Human class with an "IMoveBehavior" simply because it would be better to abstract that into a "WorldEntity" abstract class.
You might have invisible entities that control things like autosaves, triggers, lighting, etc, but some will have a position in the world. These are the ones who will have a vector identifying their position. Have the AI's Think() method call its own move() method, but keep it private. The only one who needs to think about moving is the AI itself.
If you want to encourage the AI to move outside of the Think) method, I would suggest some kind of imperative, such as a Goal-Oriented Action Planning (GOAP) system. Jeff Orkin wrote about this fantastic concept, and it was used in games such as F.E.A.R. and Fallout 3. It might be a bit overkill for your application, but I thought it was interesting.
http://web.media.mit.edu/~jorkin/goap.html

Designing Game Objects

I recently started working on a small game for my own amusement, using Microsoft XNA and C#. My question is in regards to designing a game object and the objects that inherit it. I'm going to define a game object as something that can be rendered on screen. So for this, I decided to make a base class which all other objects that will need to be rendered will inherit, called GameObject. The code below is the class I made:
class GameObject
{
private Model model = null;
private float scale = 1f;
private Vector3 position = Vector3.Zero;
private Vector3 rotation = Vector3.Zero;
private Vector3 velocity = Vector3.Zero;
private bool alive = false;
protected ContentManager content;
#region Constructors
public GameObject(ContentManager content, string modelResource)
{
this.content = content;
model = content.Load<Model>(modelResource);
}
public GameObject(ContentManager content, string modelResource, bool alive)
: this(content, modelResource)
{
this.alive = alive;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale)
: this(content, modelResource, alive)
{
this.scale = scale;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: this(content, modelResource, alive, scale)
{
this.position = position;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: this(content, modelResource, alive, scale, position)
{
this.rotation = rotation;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: this(content, modelResource, alive, scale, position, rotation)
{
this.velocity = velocity;
}
#endregion
}
I've left out extra methods that do things such as rotate, move, and draw the object. Now if I wanted to create another object, like a ship, I'd create a Ship class, which would inherit GameObject. Sample code below:
class Ship : GameObject
{
private int num_missiles = 20; // the number of missiles this ship can have alive at any given time
private Missile[] missiles;
private float max_missile_distance = 3000f; // max distance a missile can be from the ship before it dies
#region Constructors
public Ship(ContentManager content, string modelResource)
: base(content, modelResource)
{
InitShip();
}
public Ship(ContentManager content, string modelResource , bool alive)
: base(content, modelResource, alive)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale)
: base(content, modelResource, alive, scale)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: base(content, modelResource, alive, scale, position)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: base(content, modelResource, alive, scale, position, rotation)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: base(content, modelResource, alive, scale, position, rotation, velocity)
{
InitShip();
}
#endregion
}
Again, I've left out any extra Ship-specific methods, like firing a missile. Do you think that this sort of design is good or should it be improved somehow or changed completely? It seems like the constructors for child classes is messy, but maybe that's the only way to do it. I've never done anything like this and am wondering if I'm way off track.
Thanks to everyone that left an answer. They were all very helpful. There seems to be a general consensus that changing it around to use an MVC pattern would be best. I'm going to look further into exactly how to do that. I'll also be removing most of the constructors and will have just one constructor, because all of the arguments after modelResource aren't necessary to create the object, and they can all be changed later through method calls.
Personally I find the sheer number of constructors you have a little offputting, but that's your choice, nothing fundamentally wrong with it :)
With regards to the general strategy of deriving game objects from a common base, that's a pretty common way to do things. Standard, even. I've tended to start using something far more akin to MVC, with incredibly lightweight "model" game objects that contain only data.
Other common approaches I've seen in XNA include / things you may want to consider:
Implementation of an IRenderable interface rather than doing any render code in the base or derived classes. For instance, you may want game objects that are never rendered - waypoints or somesuch.
You could make your base class abstract, you're not likely to want to ever instantiate a GameObject.
Again though, minor points. Your design is fine.
Not only is the number of constructors a potential issue (especially having to re-define them for each derived class) - but the number of parameters to the constructor can become an issue. Even if you make the optional parameters nullable, it becomes difficult to read and maintain the code later.
If I write:
new Ship(content, "resource", true, null, null, null, null);
What does the second NULL do?
It makes code more readable (but more verbose) to use a structure to hold your parameters if the parameter list goes beyond four or five parameters:
GameObjectParams params(content, "resource");
params.IsAlive = true;
new Ship(params);
There are a lot of ways this can be done.
Since you are asking a design-related question, I will try to give some hints on that, rather than on the lots of code you posted, because others have already started on that.
Games lend themselves very much to the Model-View-Controller pattern. You are explicitly talking about the display part, but think about it: you have vectors in there, etc., and that usually is part of what you are modelling. Think of the game world and the objects in there as the models. They have a position, they might have velocity and direction. That's the model part of MVC.
I noticed your wish to have the ship fire. You will probably want the mechanic to make the ship fire in a controller class, something that takes keyboard input, for example. And this controller class will send messages to the model-part. A sound and easy think you will probably want is to have some fireAction()-method on the model. On your base-model, that might be an overridable (virtual, abstract) method. On the ship it might add a "bullet" to the game world.
Seeing how I wrote about behaviour of your model so much already, here's another thing that has helped me plenty: use the strategy pattern to make behaviour of classes exchangeable. The strategy pattern is also great if you think AI and want behaviour to change somewhen in the future. You might not know it now, but in a month you might want ballistic missiles as the default missiles and you can easily change that later if you had used the strategy pattenr.
So eventually you might want to really make something like a display class. It will have primitives like you named: rotate, translate, and so on. And you want to derive from it to add more functionality or change functionality. But think about it, once you have more than a ship, a special kind of ship, another special kind of ship, you'll run into derivation hell and you will replicate a lot of code. Again, use the strategy pattern. And remember to keep it simple. What does a Displayble class need to have?
Means to know its position relative to the screen. It can, thanks to the model of its in-world object and something like the gameworld's model!
It must know of a bitmap to display for its model and its dimensions.
It must know if anything should prevent it from drawing, if that is not handled by the drawing engine (i.e. another object occluding it).
This design doesn't separate the UI parts of an object and the behavior parts of an object, the "model" and "view" so to speak. This is not necessarily a bad thing, but you might find the following refactorings difficult if you continue with this design:
Re-skinning the game by changing all the art assets
Changing the behavior of many different in-game objects, for example the rules that determine whether or not an object is alive
Changing to a different sprite engine.
But if you are OK with these tradeoffs and this design makes sense to you, I see nothing egregiously wrong with it.
I am very interested in your storing method for rotation in a vector. How does this work?
If you store the angles of X,Y,Z-axis (so called Euler-angles), you should rethink this idea, if you want to create a 3D game, as you will meet shortly after your first rendering the evil GIMBAL LOCK
Personally I do not like so much constructors there, as you can provide 1 constructor and set all not needed params to null. in this way your interface stays cleaner.
I also heavily recommend looking into a component based design using composition rather than inheritance. The gist of the idea is to model object based on their underlying properties, and allow the properties to do all of the work for you.
In your case, a GameObject may have properties like being able to move, being renderable, or having some state. These seperate functions (or behaviors) can be modeled as objects and composed in the GameObject to build the functionality you desire.
Honestly though, for a small project you're working on I would focus on making the game functional rather than worry about details like coupling and abstraction.
Depending on how often the constructors would be called, you could consider making all the extra parameters nullable and just passing null to them when they don't have values. Messier creating the objects, fewer constructors
I went down this path when first creating games in XNA, but next time I would do more of a model/view type of approach. The Model objects would be what you deal with in your Update loop, and your Views would be used in your Draw loop.
I got in trouble with not separating the model from the view when I wanted to use my sprite object to handle both 3D and 2D objects. It got real messy real quick.
The people here talking about separating Model from View are correct. To put it in more game developer oriented terms, you should have separate classes for GameObject and RenderObject. Think back to your main game loop:
// main loop
while (true) {
ProcessInput(); // handle input events
UpdateGameWorld(); // update game objects
RenderFrame(); // each render object draws itself
}
You want the process of updating your game world and rendering your current frame to be as separate as possible.
Alternatively you can make a struct or helper class to hold all the data and have the many constructors in the struct, that way you only have to have tons constructors in 1 object rather than in every class that inherits from GameObject
First game? Start simple. Your base GameObject (which in your case is more appropriately called DrawableGameObject [note the DrawableGameComponent class in XNA]) should only contain the information that belongs to all GameObjects. Your alive and velocity variables don't really belong. As others have mentioned, you probably don't want to ever be mixing your drawing and update logic.
Velocity should be in a Mobile class, which should handle the update logic to change the position of the GameObject. You may also want to consider keeping track of acceleration, and having that steadily increase as the player holds a button down, and steadily decrease after the player releases the button (instead of using a constant acceleration)... but that's more a game design decision than a class organization decision.
What "alive" means can be very different based on context. In a simple space shooter, something that isn't alive should probably be destroyed (possibly replaced with a few chunks of space debris?). If it's a player that respawns, you're going to want to make sure the player is separate from the ship. The ship doesn't respawn, the ship is destroyed and the player gets a new ship (recycling the old ship in memory instead of deleting it and creating a new one will use fewer cycles - you can simply either move the ship into no-man's-land or pull it out of your game scene entirely and put it back after respawn).
Another thing that you should be wary of... Do not let your players look directly up or down on your vertical axis, or you'll run into, as Peter Parker mentioned, Gimbal Lock issues (which you do not want to mess with if you're doing game development for fun!). Better yet... start with 2D (or at the very least, limit movement to only 2 dimensions)! It's a lot easier when you're new to game development.
I'd suggest following the XNA Creators Club Getting Started Guides before doing any more programming, however. You should also consider looking for some other more general game development guides to get a few alternative suggestions.

Categories