Reputation: 130
I have a "car" which has to be moved in the direction which it is rotated. Now it just rotates in a direction and keeps on going up and down.Please help me. I am using adobe flash pro cs6 and actionscript3. My code is :
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
car.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
car.y += 5;
}
if (downPressed)
{
car.y -= 5;
}
if (rightPressed)
{
car.rotation += 5;
}
if (leftPressed)
{
car.rotation -= 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
}
Upvotes: 0
Views: 1263
Reputation: 52133
You need to use vector math to move the car's x,y
based on an angle and a distance.
For example, you could move your car based on an angle and speed like this:
function move(degrees:Number, speed:Number):void {
var radians:Number = degrees * (Math.PI / 180);
car.x += Math.cos(radians) * speed;
car.y += Math.sin(radians) * speed;
}
Then you can use the car's rotation
as the angle and 5
or -5
as the speed:
if (upPressed) {
move(car.rotation, 5);
}
if (downPressed) {
move(car.rotation, -5);
}
Note that this assumes rotation=0
means your car is facing right-ward. If you've draw your car facing a different direction you'll need to compensate for the angle you've drawn the car, for example if the car is facing upward you need to use move(car.rotation - 90, 5)
.
Upvotes: 1