Box2D C++ tutorials - Making a test

Last edited: July 14 2013

Chinese version -> 中文

Making your own test


Let's add a test to the testbed, just a simple one that doesn't do much to start with but will serve as an example to look at all the places we need to edit.

First we'll need a subclass of the Test class to define the test itself. In the Testbed/Tests folder you should find a whole bunch of .h files with names similar to the tests you see in the testbed. In this folder, add another .h file of your own, with a clever name like uhh... FooTest. For now, we'll just make an empty test which shows some text at the top of the screen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #ifndef FOOTEST_H
  #define FOOTEST_H
    
  class FooTest : public Test
    {
        public:
        FooTest() { } //do nothing, no scene yet
    
        void Step(Settings* settings)
        {
            //run the default physics and rendering
            Test::Step(settings); 
    
            //show some text in the main screen
            m_debugDraw.DrawString(5, m_textLine, "Now we have a foo test");
            m_textLine += 15;
        }
    
        static Test* Create()
        {
            return new FooTest;
        }
    };
  
  #endif
The above class does not override any input functions, and doesn't set up a scene either. The Step() function is overridden, and uses the variable m_debugDraw of the parent class as a handy way to get some information on the screen. Another variable from the parent class, m_textLine is used here to increment the text drawing position, you would need to do this if you want to show more than one line of text without having them all on top of each other. The Create() function gives an instance of this class to the testbed framework when necessary.

Now to add this to the testbed, the file TestEntries.cpp in the same folder needs a couple of lines added:
1
2
3
  #include "FooTest.h"
    
        {"Foo test", FooTest::Create},
These additions will go next to the existing lines of the same type which are already there. Take a look in the file and it will be pretty clear what I mean.

Now build the project again and run it. You should see your 'Foo test' option at the bottom of the drop-down list, and when selected the test should run and appear like this:
Foo test
If you want your test to be selected by default when the testbed app starts up, just put the FooTest::Create line at the top of it's list.


Next: Bodies