我创建了一个dynamic_body
并且我想使用一个移动那个身体EventListener
。但是,我无法访问正文,并且我的代码中ApplyImpulse()
的函数或函数存在问题。ApplyForce()
但我看不到它。我错过了什么?
function init() {
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2AABB = Box2D.Collision.b2AABB
, b2BodyDef = Box2D.Dynamics.b2BodyDef
, b2Body = Box2D.Dynamics.b2Body
, b2FixtureDef = Box2D.Dynamics.b2FixtureDef
, b2Fixture = Box2D.Dynamics.b2Fixture
, b2World = Box2D.Dynamics.b2World
, b2MassData = Box2D.Collision.Shapes.b2MassData
, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
, b2DebugDraw = Box2D.Dynamics.b2DebugDraw
, b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef
;
var world = new b2World(
new b2Vec2(0, 0) //gravity
, true //allow sleep
);
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new b2BodyDef;
//creating ground
bodyDef.type = b2Body.b2_staticBody;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(20, 2);
bodyDef.position.Set(10, 500 / 30 + 1.8);
world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(10, -1.8);
world.CreateBody(bodyDef).CreateFixture(fixDef);
fixDef.shape.SetAsBox(2, 14);
bodyDef.position.Set(-1.8, 13);
world.CreateBody(bodyDef).CreateFixture(fixDef);
bodyDef.position.Set(25, 13);
world.CreateBody(bodyDef).CreateFixture(fixDef);
// creating body
playerbody = new b2BodyDef;
playerbody.type = b2Body.b2_dynamicBody;
bodyfix = new b2FixtureDef;
bodyfix.shape = new b2PolygonShape;
bodyfix.shape.SetAsBox(
0.4 //half width
, 0.6 //half height
);
playerbody.position.x = 3.2;
playerbody.position.y = 14;
bodyfix.body = playerbody;
bodyA = world.CreateBody(playerbody).CreateFixture(bodyfix);
function aPressed() {
var direction = new b2Vec2(-5,0);
bodyA.ApplyImpulse( direction , bodyA.GetWorldCenter());
}
function dPressed() {
var direction = new b2Vec2(5,0);
bodyA.ApplyImpulse( direction , bodyA.GetWorldCenter());
}
function spacePressed() {
var direction = new b2Vec2(0,5);
bodyA.ApplyImpulse( direction , bodyA.GetWorldCenter());
}
function ctrlPressed(){
var direction = new b2Vec2(0,-2);
bodyA.ApplyImpulse( direction , bodyA.GetWorldCenter());
}
// keyboard controls
document.addEventListener('keypress',function(event) {
var keycode = event.keyCode;
switch (keycode){
case 65:
aPressed();
break;
case 68:
dPressed();
break;
case 32:
spacePressed();
break;
case 17:
ctrlPressed();
break;
}
},false);