7

I'm working on a importer for a game of mine, it reads an xml and then creates the box2d bodies for everything.

For example

  <polygon vertexCount="3" density="0" friction="0.25" restitution="0.30000000000000004">
      <vertice x="6.506500000000001" y="0.4345"/>
      <vertice x="6.534970527648927" y="0.48385302734375"/>
      <vertice x="6.478029472351075" y="0.48385302734375"/>
  </polygon>

The problem is in the exporter I'm now facing the polygon part, I need to setup a b2vec2 array before adding the vertices and setting their positions.

int count = [[childnode attributeForName:@"vertexCount"] intValue];
b2Vec2 points[count];

but box2d wants the points[5] to be an actual literal number (like points[5] instead of a variable points[number], the error it outputs when I have the variable count in there is:

 Variable length array of non-POD element type 'b2Vec2'

How do I solve this? I tried making it a constant but that doesn't work either (and doesn't help me since I need it to be dynamic).

Jonas
  • 121,568
  • 97
  • 310
  • 388
M0rph3v5
  • 945
  • 1
  • 11
  • 23

2 Answers2

19

You have to create the array on a heap:

b2Vec2 *array = new b2Vec2[count];

Don't forget to delete the array manually when finished.

or better use std::vector:

a)
std::vector<b2Vec2> vertices(count);
vertices[0].set(2, 3);
vertices[1].set(3, 4);
...

b)
std::vector<b2Vec2> vertices;
vertices.push_back(b2Vec2(2, 3));
vertices.push_back(b2Vec2(3, 4));
Andrew
  • 24,218
  • 13
  • 61
  • 90
  • doesn't seem to work, crashes in the b2PolygonShape.cpp. What I eventually did was set the .m_vertexCount manually and then just set them with .m_verticles[i].Set(x,y); – M0rph3v5 Jul 26 '11 at 11:36
  • to be exact, it failed at: b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); – M0rph3v5 Jul 26 '11 at 11:45
  • check that you haven't put two vertices of the polygon in the exact same place – iforce2d Jul 26 '11 at 18:43
  • it's working fine with the manual .m_vertexCount and .m_vertices[i].Set with the same points so I doubt there's anything wrong with that. – M0rph3v5 Jul 26 '11 at 20:24
-3

Took the easier route and accessed the not suppose to vars:

polygonShape.m_vertexCount = count;

and then set them in the forloop:

polygonShape.m_vertices[c].Set(x,y);

it's working perfectly fine :)

M0rph3v5
  • 945
  • 1
  • 11
  • 23