: : 1 Thread per object is very poor design, since that would in some
: : cases mean that you can have 1000+ threads. 1000+ threads is a huge
: : drain on resources and takes a huge amount of time to synchronize,
: : making the game sluggish to say the least.
: : Game developers usually use a game loop, and iterate within that
: : loop across all the necessary objects. In pseudocode:
: :
: :
: : repeat
: : Move Player
: : for each movable object
: : if object is alive then
: : move object
: : if collides with another then
: : handle collision
: : if object is dying then
: : next death sequence step
: : endfor
: : update screen
: : until game is ended
: :
: :
: : As you can see, this turns an seemingly active game into a
: : turn-based game, where each "player" gets a go. Ideally this loop
: : runs 25-29 times per second giving the impression of fluid motion.
: : All too often games run at less than that due to lack of processing
: : power of the hardware.
: : As you also can see, this can easily be coded in 1 thread. This
: : greatly reduces (or better eliminates) the need for
: : thread-synchronization and resource-locking, freeing up resources
: : which can be used to improve the game itself.
:
: Okay but what if I want the objects to move individually? Don't I
: have to create a diffrent thread for diffrent movement? Also how
: would I create an object in a single thread in pseudo code. Should
: it look for them in an array?
You can use an array or linked-list to store the individual objects.
You don't need extra threads for individual movements. Here's a bigger example (again in pseudo code):
class movable {
int direction, x, y
int oldx, oldy
move() {
oldx = x;
oldy = y;
switch (direction) {
case up: y = y + 1
case down: y = y - 1
}
}
draw() {
draw(x, y)
}
clear() {
draw(oldx, oldy)
}
draw(int x, int y) {
XORDraw(x, y, icon)
}
}
class missile extends movable {
move() {
switch (direction) { // Missiles move very fast
case up: y = y + 3
case down: y = y - 3
}
}
}
main() {
repeat
switch (Player input) {
case up: player.direction = up;
case down: player.direction = down;
case s: movables.add(new missile(player.x, player.y))
}
for (i = 0; i < movables.length; i++) {
movables[i].move() // each movable makes 1 step
}
for (i = 0; i < movables.length; i++) {
movables[i].clear() // remove previous location on screen
movables[i].draw() // draw icon at the new location on screen
}
until game ended
}
In each repeat-loop iteration, each movable object makes 1 step at their speed in the direction it is moving. Because every movable object keeps track of their own location and direction, every object appears to be moving independently of eachother.
Since the screen is updated after every movable object has gotten a new location, it appears that all movable objects have moved simultaneously.
The frame rate of the game is determined by the time each iteration of the loop takes.