Game Development Reference
In-Depth Information
Controlling motors with keyboard
We want the player to control the truck with arrow keys. Left arrow key will move
the truck to the left and right arrow key will move the truck to the right.
1. To let the player control motors with keyboard, you first need to include the
KeyboardEvent class, which will allow us to create keyboard listeners:
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import Box2D.Dynamics.*;
import Box2D.Collision.*;
import Box2D.Collision.Shapes.*;
import Box2D.Common.Math.*;
import Box2D.Dynamics.Joints.*;
2.
Then, we need some new class-level variables:
private var world:b2World;
private var worldScale:Number=30;
private var left:Boolean=false;
private var right:Boolean=false;
private var frj:b2RevoluteJoint;
private var rrj:b2RevoluteJoint;
private var motorSpeed:Number=0;
left and right are Boolean variables, which will let us know if left or right
arrow keys are being pressed.
frj and rrj are the front and rear revolute joint respectively. Variable names
are a bit confusing, but I had to use as few characters as I could to give them
names for a layout purpose.
motorSpeed is the current motor speed, initially set at zero.
3.
In the Main function now we add the listeners to trigger when the player
presses and releases a key:
public function Main() {
world=new b2World(new b2Vec2(0,5),true);
debugDraw();
ground();
var frontCart:b2Body=addCart(200,430,true);
var rearCart:b2Body=addCart(100,430,false);
var dJoint:b2DistanceJointDef=new b2DistanceJointDef();
dJoint.bodyA=frontCart;
dJoint.bodyB=rearCart;
dJoint.localAnchorA=new b2Vec2(0,0);
 
Search WWH ::




Custom Search