Updating Objects

Started by
2 comments, last by Silviu Andrei 12 years, 5 months ago
I would like some quick advice on the proper or good way to manage something.

Just as a quick example lets say it is a simple 2D side scroller where the player and enemy can shoot each other. Both projectiles are the exact same they just move in different directions. What would be the proper way to update this projectile so all I have to do is just call like projectile.Update() for both a player projectile and enemy projectile?

Would it be best to just pass a parameter into the update function to say where the fire event came from and handle the different cases in the update function, or what?

This is just a simple little design issue that always seems to plague me when I start a larger project.

Thanks.

PS, This is really a design question not really on how to do something.
Advertisement
If you are in an object oriented language, you could define a class Projectile, and then create two instances of it - playerProjectile and enemyProjectile. Then you can call playerProjectile.update() and enemyProjectile.update(). So you can do the necessary operations inside the update method, and you are not forced to pass "state" parameters since each object "knows" its state.

If you are not in an object oriented language you are right, you should "emulate" this using parameters.

[ About me ]

Yea, that I was going to do already.

I guess what should be asked though is what should be in the update function? Since the projectiles will be traveling in different directions when fired from the player and enemy then the movement code will be different. Does the movement code need to be in a different place or am I looking at it wrong?

Simple little design things like this for some reason always get to me and when I do larger projects I always end up creating spaghetti code if stuff like this isn't managed properly.
You could store in the class the velocity vector and the position. Suppose your screen top-left corner has the coordinates [0, 0] and the bottom-left corner [1, 1]. Then you would instantiate 2 objects of your Projectile class with velocity vectors like (0.1, -0.1) and (-0.1, -0.1). That way your projectiles will both travel up and in opposite horizontal directions. You could pass to the Update function the elapsed time in seconds since the last Update call. Then your Update function and your class would look something like this:


class Projectile
{
Vector2 VelocityVector;
Vector2 Position;

Projectile(Vector2 velocityVector, Vector2 initialPosition)
{
VelocityVector = velocityVector;
Position = initialPosition;
}

void Update(double elapsedSeconds)
{
Position += VelocityVector * elapsedSeconds;
}
}

This topic is closed to new replies.

Advertisement