I would like to move a kinematic box by pressing the down arrow. As is noted by the console logs, the keydown actually does change the box's velocity... but for reasons beyond my grasp it still doesn't move.
Note that if you place the SetLinearVelocity() call in a spot where it runs immediately, the box will move, but if it is in a setTimeout, or as in my example, called from an event, the box stays frozen despite its y velocity property changing to 1.
I created the simplest example I could to show my problem.
Note: I am using the latest release of Box2dWeb
//std variables
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2BodyDef = Box2D.Dynamics.b2BodyDef
, b2Body = Box2D.Dynamics.b2Body
, b2FixtureDef = Box2D.Dynamics.b2FixtureDef
, b2Fixture = Box2D.Dynamics.b2Fixture
, b2World = Box2D.Dynamics.b2World
, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
, b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
//create world and gravity
var world = new b2World(
new b2Vec2(0, 10)
, true
);
//fixture defs
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = .2;
//body defs
var bodyDef = new b2BodyDef;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(2,2);
bodyDef.type = b2Body.b2_kinematicBody;
bodyDef.position.x = 3;
bodyDef.position.y = 0;
//body and fixture creation
var body1 = world.CreateBody(bodyDef);
body1.CreateFixture(fixDef);
//"Before" console log
console.log("Claimed velocity before down is pressed: " + body1.GetLinearVelocity().y);
//Listener and keycode switch for intended velocity change
window.addEventListener("keydown", onKeyDown, false);
function onKeyDown(e) {
switch(e.keyCode) {
case 40://down
body1.SetLinearVelocity(new b2Vec2(0,1));
console.log("Claimed velocity after down is pressed: " + body1.GetLinearVelocity().y);
}
}
//debug drawing
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(30.0);
debugDraw.SetFillAlpha(0.5);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update, 1000 / 60);
//loop
function update() {
world.Step(1 / 60, 10, 10);
world.DrawDebugData();
world.ClearForces();
}