VBfx / Common / Types

Introduction

What is a Type and what do I need it for? Basically a Type is nothing more than a collection of variables. Imagine a simple ball game like Pong. You'd have something like this to hold the ball's position and speed:

Dim BallX as Long
Dim BallY as Long
Dim SpeedX as Long
Dim SpeedY as Long

Now Pong is quite an easy and boring game, so why not improve it a little. Let's say we want a second ball, how would you solve this problem? Well of course you could just do the same thing again:

Dim Ball2X as Long
Dim Ball2Y as Long
Dim Speed2X as Long
Dim Speed2Y as Long

Not to mention that you'll have to double each function for moving the ball, checking collisions and such. Still not convinced? Ok then, let's say we want 100 balls! - Sure we won't need 100 balls in a Pong game but what about 100 shots in a action game? Just keep on reading...

Using Types

As already mentioned a Type is a collection of variables, we'll call them properties from now on. Let's take the same example again and make a Type out of it:

Private Type tBall
    X as Long
    Y as Long
    SpeedX as Long
    SpeedY as Long
End Type

This Type called tBall (the t stands for Type) contains 4 properties. Often Types are called UDT (user-defined type) because you define them by yourself. However we can't yet use it since it's just a data type and not a variable. So we need another line where we declare the ball variable:

Dim Ball as tBall

See the last part? We declared the Ball as a new tBall. This means that Ball now has all properties from the tBall Type and you can access them as usual:

Ball.X = 10
Ball.Y = 20
'etc.

Now adding another ball won't be such a big problem, you could just declare a new variable Ball2 as a tBall. Still wonder how to manage 100 balls at once? Well since we declared a new data type we can simply make an array of balls now:

Dim Balls(100) as tBall

And that's it. You can now use a loop to iterate trough each ball and move it, check collision, draw it or whatever.

Download

The demo project shows 20 balls moving around using Types as described above. There's a cheap collision detection to keep the balls in screen, shouldn't be too hard to understand though...

Navigation