xxxxxxxxxx
146
//enumeration of possible input states
const
MS_STOP = 1,
MS_LEFT = 2,
MS_RIGHT = 3;
var body;
var moveState;
var EXAMPLE = 0;
function setup() {
createCanvas(400, 300);
//30 is the conversion factor for pixel coordinates
//box2d recommends shape edges between 0.1 and 10
b2newWorld(30, b2V(0, 9.8));
new b2Body('chain', false, b2V(width / 2, height - 8),
[b2V(-width / 2 + 8, -height + 16), b2V(-width / 2 + 8, 0), b2V(width / 2 - 8, 0), b2V(width / 2 - 8, -height + 16), b2V(-width / 2 + 8, -height + 16)]);
body = new b2Body('box', true, b2V(width / 2, 16), b2V(20, 20));
moveState = MS_STOP;
}
function keyPressed() {
switch (key) {
case 'q': //move left
moveState = MS_LEFT;
break;
case 'w': //stop
moveState = MS_STOP;
break;
case 'e': //move right
moveState = MS_RIGHT;
break;
case 'g': //switch from first example to fifth
EXAMPLE = ++EXAMPLE % 6;
break;
}
}
var states = ['absLinearVelocity', 'gradualLinear', 'force', 'gradualForce', 'impulse', 'gradualImpulse'];
function draw() {
var force;
background(227);
text('state=' + states[EXAMPLE], 20, 30);
text('type g to step through the 6 states', 170, 30);
text('type q to move left, w to stop, e to move right',120,45);
text(body.toString(), 20, 45);
//inside Step()
var vel = body.linearVelocity;
if (EXAMPLE == 0) {
switch (moveState) {
case MS_LEFT:
vel.x = -5;
break;
case MS_STOP:
vel.x = 0;
break;
case MS_RIGHT:
vel.x = 5;
break;
}
body.linearVelocity = vel;
}
if (EXAMPLE == 1) {
switch (moveState) {
case MS_LEFT:
vel.x = max(vel.x - 0.2, -5.0);
break;
case MS_STOP:
vel.x *= 0.98;
break;
case MS_RIGHT:
vel.x = min(vel.x + 0.2, 5.0);
break;
}
body.linearVelocity = vel;
}
if (EXAMPLE == 2) {
force = 0;
switch (moveState) {
case MS_LEFT:
if (vel.x > -5) force = -50;
break;
case MS_STOP:
force = vel.x * -10;
break;
case MS_RIGHT:
if (vel.x < 5) force = 50;
break;
}
body.force = b2V(force, 0);
}
if (EXAMPLE == 3) {
var desiredVel = 0;
switch (moveState) {
case MS_LEFT:
desiredVel = -5;
break;
case MS_STOP:
desiredVel = 0;
break;
case MS_RIGHT:
desiredVel = 5;
break;
}
var velChange = desiredVel - vel.x;
force = body.body.getMass() * velChange / (1 / 60.0); //f = mv/t
if (force != 0)
body.force = b2V(force, 0);
}
if (EXAMPLE == 4) {
var desiredVel = 0;
switch (moveState) {
case MS_LEFT:
desiredVel = -5;
break;
case MS_STOP:
desiredVel = 0;
break;
case MS_RIGHT:
desiredVel = 5;
break;
}
var velChange = desiredVel - vel.x;
var impulse = body.body.getMass() * velChange; //disregard time factor
if (impulse != 0)
body.impulse = b2V(impulse, 0);
}
if (EXAMPLE == 5) {
var desiredVel = 0;
switch (moveState) {
case MS_LEFT:
desiredVel = max(vel.x - 0.2, -5.0);
break;
case MS_STOP:
desiredVel = vel.x * 0.98;
break;
case MS_RIGHT:
desiredVel = min(vel.x + 0.2, 5.0);
break;
}
var velChange = desiredVel - vel.x;
var impulse = body.body.getMass() * velChange; //disregard time factor
body.impulse = b2V(impulse, 0);
}
b2Update();
b2Draw();
}