0

before I started C++ I digged around in ActionScript3 for a while. The first thing I've noticed is that you apparently have to call all your objects/game-characters individually and tell them to update() for example.

My first thought was to sort them into arrays/vectors and do for-loops for efficiency since I don't know about C++ events yet but I'm curious what you guys are doing!

Can you use Recursive functions inside the class to make it work independently?

Let's say I'd want to animate a tree with a spritesheet. Would I have to call the tree's update() every frame or can I tell the object to get stuck in a Recursive loop and handle the animations itself?

Farrrbi
  • 3
  • 1

1 Answers1

2

Well, you could use a separate thread to execute an object's update function in a loop, but that's a really bad idea. Not only will performance suffer when a system executes more threads than it has CPU cores (thread switches are expensive), but also because it leads to bugs.

Adobe Flash executes the update-function of all objects at a controlled point of the application where the state of the rendering system is consistent. But with C++ timers and threads you would have no control over when that update is executed. When you have bad luck, one object reads data which another object is currently writing and reads a weird inconsistent state. This is called a race condition and leads to bugs which happen extremely rarely and seemingly at random, making them impossible to reproduce and debug. There are ways to deal with this, like semaphores, mutexes or critical sections, but they have their own pitfalls, like deadlocks.

Multithreading in C++ is a very advanced concept full of non-obvious problems. As a beginner you are well-advised to leave your hands off of it for now and write your game completely single-threaded.

The normal solution is to have a main thread which alternates between calling a global update() function and a global render() function. The global update() would then call the update-function of every object in the game in a for-loop. There are two ways to structure this main loop. Which one you pick is a rather religious question which is further elaborated on in the question "When should I use a fixed or variable time step?".

Glorfindel
  • 986
  • 1
  • 9
  • 16
Philipp
  • 119,250
  • 27
  • 256
  • 336