Something's not right (Sumo Robo Simulator)

Alright, I'm working on a project for school. Were it not for that I'd be doing this in C++. But the teacher uses Java so this project has to be java. I'm extending a program he had written previously to use jBox2D for more realistic physics. It's a top down sumo robot simulator where the students can extend a robot class, write their own algorithm to react to the stimuli in the ring, and then the robot is imported into the simulator and run against other robots.

I've ripped out his old spagetti code and put my own in. I've tried to use the Testbed examples to get this right, tho none of them have objects with constantly changing and potentially alterable thrust except for collisions.

So what I'm trying to do is have each robot have a left and right wheel in the middle of their spherical bodies. They can alter course by altering the drive of the left and right wheels. But when I set everything up the way I think it needs to be I lose contact with the objects once I put them in the world. It seems to me that there's a disjoint between the objects in the world and the variables that I put them in with... am I making sense. maybe I should just show some code:

Code:
public class RobotPose {
    protected Robot robot;
    protected Body body;
    protected BodyDef loc;
    protected Body leftwheel;
    protected Body rightwheel;

    public RobotPose(World world, Robot r, float x, float y, float angle) throws Exception {
        robot = r;

        PolygonDef bodyShape = new PolygonDef();
        bodyShape.setAsBox(2f*(float)robot.HALFWIDTH, 2f*(float)robot.HALFWIDTH);
        bodyShape.density = 1.0f;
        loc = new BodyDef();
        bodyShape.friction = .3f;
        bodyShape.restitution = 0.65f;

        BodyDef lw = new BodyDef();
        PolygonDef lwheel = new PolygonDef();
        leftwheel = world.createBody(lw);
        leftwheel.createShape(lwheel);
        lwheel.density = 0f;
        lwheel.setAsBox((float)robot.HALFWIDTH / 8, (float)robot.HALFWIDTH);
       
        BodyDef rw = new BodyDef();
        PolygonDef rwheel = new PolygonDef();
        rightwheel = world.createBody(rw);
        rwheel.setAsBox((float)robot.HALFWIDTH / 8, (float)robot.HALFWIDTH);
        rwheel.density = 0f;
        rightwheel.createShape(rwheel);

        loc.angle = (float)(Math.PI * angle/180);
        loc.position = new Vec2(x, y);
        body = world.createBody(loc);
        body.createShape(bodyShape);
        RevoluteJointDef leftjoint = new RevoluteJointDef();
        leftjoint.initialize(body, leftwheel, new Vec2(-(float)(3 * Robot.HALFWIDTH / 4),0));
        leftjoint.enableMotor = true;
        leftjoint.maxMotorTorque = 100f;
        RevoluteJointDef rightjoint = new RevoluteJointDef();
        rightjoint.initialize(body, leftwheel, new Vec2(-(float)(3 * Robot.HALFWIDTH / 4),0));
        rightjoint.enableMotor = true;
        rightjoint.maxMotorTorque = 100f;
        world.createJoint(leftjoint);
        world.createJoint(rightjoint);

        body.setMassFromShapes();
        body.m_mass = (float)robot.getMass(); // Override calculated data
        loc.angle = (float)(Math.PI * angle/180);
    }
//snippy snip

Now, firs of all, am I right that this creates 2 wheels and attaches them to the body in such a way that when the wheels move they move the body? Also, theoretically I should be able to turn the wheel in the following manner:
Code:
    public void run () {
        float right = 0, left = 0;
        if ((robot.rightWheel == 0) && (robot.leftWheel == 0)) {
            left = 2;
            right = 1;
        } else {
            left = (float)robot.getLeftWheel();
            right = (float)robot.getRightWheel();
        }
        leftwheel.setLinearVelocity(new Vec2(0, left));
        rightwheel.setLinearVelocity(new Vec2(0, right));
    }
}

(Which coincidentally is the continuation of the code above) and it should move, right? Unfortunately it doesn't.

I'm attaching the rest of the source so that if anyone is inclined to open it up and give me a hand they could. (Also, so no one can say they can't help me without the rest of the code). I'm gonna keep cracking on this, but any insight you more experienced type could offer would be appreciated.
#1: In RobotPose, your "getBody" method is returning a stored-away BodyDef. After the body is created, the BodyDef will never change. You should store the Body object instead.

#2: In SumoWorld::updateRobotPositions, you're calling world.step the wrong way - the correct ordering is world.step(timestep, iterations), and timestep should be the number of seconds.

#3: You're setting the wheel velocities to move up or down in world coordinates. This is almost definitely not what you want - you probably want to move them forward or backwards relative to their current orientations, not the global y axis. You'll want to use the Body method getWorldVector(localVector) to convert from a local direction to a world direction instead.

See if fixing those things up gets things moving - I tried your code, and something's definitely happening inside the physics engine, bodies are moving. Whether they're moving correctly is another issue, you'll probably have a little debugging left once you get these issues fixed up. Let us know if you run into problems.

Good luck!
Thanks for your help. Fixing the iterations things started to move. Just not the way I expected.

I'm new to Box2D, and inexperienced with java (C is my forte) but java is required for the project so this has been a challenge. I was using this as my sample code: viewtopic.php?p=25119#p25119 . It's in flash so I've had to make some adjustments obviously.

Okay, so if the BodyDef (and shape def I'm assuming) information is gone after it's added to the world and body objects, then how would I force my newly joined object to a specific rotational angle so that the wheels go with it? I tried using setXForm, but when I do that my objects disappear and the simulation breaks.

I tried doing the body.getWorldVector like you said, but I don't quite know how to use it properly and what to do with it. I tried to use the .setLinearVelocity... but everytime I did, once I set things up with prismatic joints, the robots suddenly disappeared, kind of like with setXForm. Is there a tutorial somewhere that will tell me how to (1) stop the motion of the body and then (2) push it with a non-centered thrust in a direction oriented to the body of the object? That's more or less what I'm trying to do here.

Re-attaching my code so you can see it in action. I won't lie, I'm hoping some philanthropic soul will take pity on me and say "do this on that line and it'll work." I know I shouldn't be hoping for this, but I am.
Cymon wrote:
Okay, so if the BodyDef (and shape def I'm assuming) information is gone after it's added to the world and body objects, then how would I force my newly joined object to a specific rotational angle so that the wheels go with it? I tried using setXForm, but when I do that my objects disappear and the simulation breaks.

Generally speaking, and doubly so when dealing with bodies connected by joints, you want to avoid the set* methods and prefer the apply* methods instead: applyForce, applyLinearImpulse, applyTorque, and applyAngularImpulse. The problem is that the set* methods pretty much bypass everything that the physics engine does internally, and can lead to strange outcomes esp. when things are connected by joints.

Quote:
I tried doing the body.getWorldVector like you said, but I don't quite know how to use it properly and what to do with it.

See below, I'll give an example. Basically, getWorldVector takes the input (say, new Vec2(0.0f, 1.0f)) and turns it so that it points in the correct direction relative to the body. For instance, if the body was rotated 90 degrees clockwise, a local (0,1) vector on the body becomes (1,0) in the world. If it was rotated 90 degrees CCW, that same vector would become (-1,0).

Quote:
I tried to use the .setLinearVelocity... but everytime I did, once I set things up with prismatic joints, the robots suddenly disappeared, kind of like with setXForm. Is there a tutorial somewhere that will tell me how to (1) stop the motion of the body and then (2) push it with a non-centered thrust in a direction oriented to the body of the object? That's more or less what I'm trying to do here.

To turn the robot, apply a torque to the robot body - body.applyTorque(torqueToApply), where torqueToApply is positive or negative based on whether you want it to turn right or left.

To move it straight ahead, do something like this:

Code:
Vec2 localAheadVector = new Vec2(0.0f, 1.0f); //may need to play with this, could be (1,0) or (-1,0), etc. depending on what "straight ahead" means for the body
Vec2 forceDirection = body.getWorldVector(localAheadVector);
float forceConstant = ... //pick something that works
Vec2 force = forceDirection.mul(forceConstant);
body.applyForce(force, body.getWorldCenter()); //applies the force at the center of mass of the body


Alternatively, depending on your needs, you could apply an impulse instead, which works similarly but gives the body a quick bump instead of a constant force (if you use a force, you'll want to apply it over many frames).

To stop the body, you can do it pretty simply by just negating all of its momentum with an impulse:
Code:
float mass = body.getMass();
// body momentum = mass * velocity
// so we want to apply an impulse (change in momentum) equal to the negative of that
Vec2 impulseToApply = body.getLinearVelocity().mul(-mass);
body.applyImpulse(impulseToApply);

If it's attached by joints to other bodies, it won't be quite enough to slow it down all the way because of the influence of the other bodies, but it should be a start.

You could also try adding more linear and angular damping (set these in the body def before you create the body), which will make all your bodies slow down quicker.

Original thread: https://box2d.org/forum/viewtopic.php?t=5377