AS3 Collision detection or Keyboard Control altering my player MovieClip path - actionscript-3

Im making a maze-like game where the player controls a movieclip (_character) around the stage with the arrows or WASD and collects things in a certain amount of time. The MovieClip has five different frames, each with their own state animations, walk Left, right, up, down and stationary.
On the stage there are squares/boxes with collision detection and I need to be able to manoeuvre around them in all different directions.
My problem is that I cant seem to get the animations inside the movieclip AND correct movement of the movieclip itself working at the same time.
My current controls can zip around the obstacles great, stops when no keys are pressed and plays relevant _character animations, but when two diagonal direction keys are pressed the MovieClip travels diagonally, even after I release one of the keys.
e.g If there is one square/box on the stage, which I want to travel clockwise around it (starting at top side) I should be able to press right, down, left, up, then right once more to return to my original position.
However with my current code I'll press right, down (and before I can press left to go around the box) my Movieclip will travel to the lower right corner of the stage (down+right).
Even if I take my finger off the DOWN key and just press RIGHT it wont correct itself and go right, its stuck in that diagonal position!
Image gives example of pressing LEFT, then DOWN as game starts.
When I remove all the boxes from the stage to test movement in an empty area, the movieclip object still becomes fixed to a diagonal direction if I push down on two buttons, with no boxes to move around it just travels to the corner of the stage it is aimed at.
Preventing this is my problem, I cant just disable multiple key presses because then it becomes too difficult to move around the maze (_character would have to be EXACTLY lined up to the gap)
Current Code:
Variables for directions
private var _bUp:Boolean = false;
private var _bDown:Boolean = false;
private var _bLeft:Boolean = false;
private var _bRight:Boolean = false;
Variables true in KeyDown Handler.
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
_bLeft=true;
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
_bRight=true;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
_bUp=true;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
_bDown=true;
}
False in KeyUp.
private function keyUpHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT
|| event.keyCode == 65 || event.keyCode == 68)
{
_bLeft=false;
_bRight=false;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP
|| event.keyCode == 87 || event.keyCode == 83 )
{
_bUp=false;
_bDown=false;
}
In the enterFrameHandler _character velocity is moved and animations play. If no keys pressed, velocity is 0 and _character is still. Then character movieclip gets the value of velocity to move, we check stage boundaries and then collisions with the boxes.
private function enterFrameHandler(event:Event):void
{
var _updown:Boolean=Boolean(!(_bUp==_bDown));
var _leftright:Boolean=Boolean(!(_bLeft==_bRight));
if (!_updown && !_leftright)
{
// not moving anywhere
_character.gotoAndStop(1);
_character.vy=0;
_character.vx=0;
}
else
{
if (_bUp)
{
_character.vy=-4;
_character.gotoAndStop(2);
}
else if (_bDown)
{
_character.vy=4;
_character.gotoAndStop(3);
}
if (_bLeft)
{
_character.vx=-4;
_character.gotoAndStop(4);
}
else if (_bRight)
{
_character.vx=4;
_character.gotoAndStop(5);
}
}
_character.x += _character.vx;
_character.y += _character.vy;
checkStageBoundaries(_character);
//Collisions
Collision.block(_character,_box1);
Collision.block(_character,_box2);
collisions with the boxes.^^^
On a side note
Not sure if its of significance but my older keyboard method only used the enterFrame Handler to link the velocity to the character object and the KeyDown Handler moved the chacters velocity. This used the same collision detection boxes but I had no problems moving the movieclip object
That code was:
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
_character.vx = -4;
_character.gotoAndStop(4);
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
_character.vx = 4;
_character.gotoAndStop(5);
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
_character.vy = -4;
_character.gotoAndStop(2);
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
_character.vy = 4;
_character.gotoAndStop(3);
}
}
// Key up handler stops velocity and plays first frame which is the stationary image.
private function keyUpHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT
|| event.keyCode == 65 || event.keyCode == 68)
{
_character.vx = 0;
_character.gotoAndStop(1);
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP
|| event.keyCode == 87 || event.keyCode == 83 )
{
_character.vy = 0;
_character.gotoAndStop(1);
}
}
This movement technique moved the MovieClip around the stage perfectly, no strange routes, but the animations wouldnt play properly with multiple key presses, so I switched to the boolean variables and enterFrame control.
In Conclusion
I have no idea if the collision detection or keyboard controls are to blame, but I would just like to be able to manoeuvre the player Movieclip quickly around the boxes and have the appropriate state animations play.
Ive seen tile based design mentioned before, but I can get what I want in the two different keyboard attempts above. Surely I can get the best of both worlds without redesigning the whole thing as tiles?! Help me please!

Got it. I didn't tell you that _character's velocity should be cleared before parsing current movement. Sorry. So, you add this:
_character.vx=0;
_character.vy=0;
into the function enterFrameHandler at its start, and this should make your char go proper way.

Related

Flash GotoFrame on Keypress

I am trying to figure out some code where when I press one of the 4 arrow keys, flash goes to a certain frame on the timeline. And when none of these keys are being pressed, it will return to its original start point on the timeline. I have seen some examples on this site, but I am struggling with it, especially returning to the original point on the timeline when there are no keypresses.
So for example :
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
function reportKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
gotoAndStop(40);
}
if (event.keyCode == Keyboard.RIGHT)
{
gotoAndStop(30);
}
if (event.keyCode == Keyboard.UP)
{
gotoAndStop (10);
}
if (event.keyCode == Keyboard.DOWN)
{
gotoAndStop (20);
}
}
stop();
I can get it to go to various points on the timeline, but I do not know how to make it return to its original point on the time line (keyframe 1) when none of those keyboard keys are being pressed.
What I am trying to do is to show on screen when a button is being pressed, and when its no longer being pressed to disapear
If anyone can help, I would be grateful. Thanks
Detect KEY_DOWN and KEY_UP events, if you want to return to the first frame when you release the keys, this could be a possible solution:
var frames:Object = {
38: 10, // Up Key
40: 20, // Down Key
37: 40, // Left Key
39: 30 // Right Key
};
stage.addEventListener(KeyboardEvent.KEY_DOWN, showMessage);
stage.addEventListener(KeyboardEvent.KEY_UP, hideMessage);
function showMessage(event:KeyboardEvent):void{
if(frames.hasOwnProperty(event.keyCode.toString())) gotoAndStop( frames[event.keyCode] );
}
function hideMessage(evt:KeyboardEvent):void{
gotoAndStop( 1 );
}

Firing bullets on a certain frame.

I could not find topic like this and that is why I am posting this question. I have a side scrolling game with the character set up in positions with frame labels- animation states to stand, jump, run, kneel and fire. She is also made to fire bullets with separate class file. The problem is that right now she is firing bullets in all of the animation states. The question is how do I make this character fire the bullets only on the frame label fire. The frame label fire consists of 2 frames and I want the launching of the bullet to happen on the second frame. Which means that the keyboard space will be pressed for a second or two before it goes to this frame and then it will fire (like in real life).
I tried to connect the animation state to the bullets somehow and tried to put the condition in these lines of code somehow:
if(e.keyCode == Keyboard.SPACE){
if (Animation state "Fire (2)")
fireBullet();
}
But it did not work, it doesn't know what I am talking about. The class file for the bullet is separate and I don't think is relevant to the problem.
The rest of the timeline code is like this:
var bulletList:Array = new Array();
if(e.keyCode == Keyboard.SPACE){
fireBullet();
}
}
function fireBullet():void
{
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
var bullet:Bullet = new Bullet(player.x - scrollX, player.y - scrollY,
playerDirection xSpeed);
back.addChild(bullet);
Thank you. I hope that my question is clear.
There is addFrameScript, AS3's mystery function that can be useful in this situation. And that would look something like this:
playerAnimation.addFrameScript( insertFrameNumber, fireBullet );
addFrameScript runs the method passed as a parameter when the MovieClip reaches a certain frame.
I believe how you would want to use this in your current code:
player.addFrameScript( 5, fireBullet );
Then in your KEY_UP handler:
function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.SPACE){
spacePressed = false;
player.gotoAndPlay("fire");
}
if(e.keyCode == Keyboard.LEFT){
leftPressed = false;
}
else if(e.keyCode == Keyboard.RIGHT){
rightPressed = false;
}
else if(e.keyCode == Keyboard.UP){
upPressed = false;
}
else if(e.keyCode == Keyboard.DOWN){
downPressed = false;
}
}

AS3 Keyboard Controlled Character - Animation problems with multiple key presses

I have a keyboard controlled character in a game which has a stationary frame when no
keys are pressed and four different animations for the up, down, left, right directions
(No diagonal movement).
So when left key is pressed, _character moves left across the screen and the left animation is played. When the key is released/Key up the stationary frame plays where the character is still.
This works fine at a slow pace but when multiple keys are being pressed to maneuver around an obstacle etc, the character often sticks to the stationary position and only plays the animations after a delay. The movement of the Movieclip is fine using velocity, but the animations suffer.
Its something to do with the key up handler surely. I’m a beginner so I’m sure I just can’t get my head around some simple logic, but I can’t figure it out! Help me please. No matter how fast I tap the keys I need that animation to play, and only when nothing is being pressed should I see the stationary image.
Character in its own class, with Velocity variables.
package
{
import flash.display.MovieClip;
import flash.display.DisplayObject
[Embed(source="../swfs/characterRes.swf", symbol="Character")]
public class Character extends MovieClip
{
//Public properties
public var vx:int = 0;
public var vy:int = 0;
public function Character()
{
}
}
}
Keydown and KeyUp listeners added.
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
In enterFrame the characters X and Y position is linked to the velocity
private function enterFrameHandler(event:Event):void
{
//Move the game character and check its stage boundaries
_character.x += _character.vx;
_character.y += _character.vy;
}
The keydown handler uses the arrows and WASD to control the velocity and plays that directions specific frame (with embedded animation)
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
_character.vx = -4;
_character.gotoAndStop(4);
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
_character.vx = 4;
_character.gotoAndStop(5);
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
_character.vy = -4;
_character.gotoAndStop(2);
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
_character.vy = 4;
_character.gotoAndStop(3);
}
}
Key up handler stops velocity and plays first frame which is the stationary image.
private function keyUpHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT
|| event.keyCode == 65 || event.keyCode == 68)
{
_character.vx = 0;
_character.gotoAndStop(1);
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP
|| event.keyCode == 87 || event.keyCode == 83 )
{
_character.vy = 0;
_character.gotoAndStop(1);
}
}
I also made the stationary image bright red to make it easier for me to spot and once I start moving the character in different directions I see Red! (literally & figuratively!)
Update
Vesper's answer has solved the animation state problem brilliantly but this new control system seems to want to travel diagonally which sends the character on an unwanted path.
My stage is a grid of 50px squares. Character is 50px and 50px boxess (with collision detection) are around with a 50px border around them so the character can maneuver around the stage.
If I press/hold one direction the character moves no problem (left to right and Up to down is fine too.), but if I go left then down or up then right etc, the character will travel that direction then continue that direction around the boxes. When I tested without the boxes the character continues in that direction diagonally.
So if I want to go clockwise around a box (starting in the bottom left side of it), I'll press up, then right and if I dont press down VERY quickly, the character will travel up and right again, towards the top right of the stage. (Character does stop if key is released.)
So if I press two keys from the opposing updown or leftright variables, it wants to travel diagonally. Any ideas how to solve this?
Final Update
Vesper's answer solved my original animation problem. I'll ask new questions to deal with remaining queries.
You actually have four de-facto independent key states, up key pressed/released, down key, left key, right key. Technically one can implement special actions in case of two opposite keys be pressed at one time, in your case it's not needed but it's still worth mentioning. So, you handle all of them separately, and only then choose where should your character face.
var bDown:Boolean=false;
var bUp:Boolean=false;
var bLeft:Boolean=false;
var bRight:Boolean=false;
// declare vars to store key states. You can use an array if you want
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == 65 )
{
bLeft=true;
// now, instead of directly attaching the movement, just set flag
}
else if (event.keyCode == Keyboard.RIGHT || event.keyCode == 68)
{
bRight=true;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == 87 )
{
bUp=true;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == 83)
{
bDown=true;
}
}
Same for key up handler, setting values to false. Now doing the parsing of the actual character's movement according to keys pressed. The best place is the enter frame handler - good thing you have it in place already.
private function enterFrameHandler(event:Event):void
{
var updown:Boolean=Boolean(!(bUp==bDown));
// if both are true or both are false, this is false. If this is true,
// we are moving upwards or downwards
var leftright:Boolean=Boolean(!(bLeft==bRight));
// same here
if (!updown && !leftright) {
// not moving anywhere
_character.gotoAndStop(1);
_character.vy=0;
_character.vx=0;
// other mechanics might be in place in case you decide to implement inertia, for example
} else {
if (bUp) {
_character.vy=-4; // hardcoding this might get you issues later
// will still do for today's task
_character.gotoAndStop(2);
} else if (bDown) {
_character.vy=4;
_character.gotoAndStop(3);
}
// one side parsed. Note, with this sequence the leftwards or rightwards
//animation supersedes up/down. But, we don't have diagonals, so there should be superseded animation
if (bLeft) {
_character.vx=-4;
_character.gotoAndStop(4);
} else if (bRight) {
_character.vx=4;
_character.gotoAndStop(5);
}
}
// Okay, now velocity and facing is set, proceed with move
//Move the game character and check its stage boundaries
_character.x += _character.vx;
_character.y += _character.vy;
}

Flash CS4/AS3: trying to make part of a movieclip loop only while keyboard button is pressed

I'm working on a project in which a character walks forwards or backwards across the screen or shoots a rifle depending on whether the user presses one of the following keyboard keys: forward arrow (key 39), back arrow (key 37) or spacebar (key 32).
My problem is that when the user presses and holds the forward arrow key, the character's movieclip plays one instance of the walking forward animation, and then moves forward. I want the walking forward animation to play throughout the entire time the character is moving.
Here is my code:
import fl.transitions.Tween;
import fl.transitions.easing.*;
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveCharacter);
stage.addEventListener(KeyboardEvent.KEY_UP, stopCharacter);
var muzzlePosition:Number = new Number();
var bullet:Bullet = new Bullet();
function moveCharacter(e:KeyboardEvent):void {
switch (e.keyCode) {
case 39 :
if (sprite_Cicada.x<stage.stageWidth-150) {
sprite_Cicada.gotoAndPlay("walk-fwd");
sprite_Cicada.x+=5;
} else {
sprite_Cicada.x+=0;
sprite_Cicada.gotoAndPlay("push");
}
break;
case 37 :
if (sprite_Cicada.x>225) {
sprite_Cicada.x-=3;
sprite_Cicada.gotoAndPlay("walk-bkwds");
} else {
sprite_Cicada.x-=0;
sprite_Cicada.gotoAndPlay("standing");
}
break;
case 32 :
muzzlePosition=sprite_Cicada.x+sprite_Cicada.AK47.x+28;
addChild(bullet);
bullet.gotoAndStop("lead");
bullet.x=muzzlePosition;
bullet.y=328;
sprite_Cicada.gotoAndPlay("fireAK");
var shootBullet:Tween=new Tween(bullet,"x",None.easeOut,muzzlePosition,stage.stageWidth*2,.5,true);
if (bullet.x>stage.stageWidth+50) {
removeChild(bullet);
}
break;
}
}
function stopCharacter(e:KeyboardEvent):void {
sprite_Cicada.gotoAndPlay("standing");
}
Perhaps you can do
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown );
stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
addEventListener(Event.ENTER_FRAME, movePerson);
function keydown(e:KeyboardEvent) {
if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT) { per_mc.gotoAndStop(2) }
if (e.keyCode == Keyboard.LEFT) {leftkeyStatus = true; rightkeyStatus = false;}
if (e.keyCode == Keyboard.RIGHT) {leftkeyStatus = false; rightkeyStatus = true;}
}
function keyup(e:KeyboardEvent) {
if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT) { per_mc.gotoAndStop(1) }
if (e.keyCode == (Keyboard.LEFT)) {leftkeyStatus = false;}
if (e.keyCode == (Keyboard.RIGHT)) {rightkeyStatus = false;}
}
function movePerson(e:Event) {
if (rightkeyStatus) {
sprite_Cicada.x-=3;
}
}

AS3 AIR - addEventListener that is in effect when the window is not in focus

this is with Flash cs6 trying to make an air app.
Hi, I'm fairly sure this is easy to answer when you know the expression.
so I want to know how to detect a KEY_DOWN and KEY_UP when the window is out of focus.
var winkeyDown:Boolean = false;
var altkeyDown:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyisDown);
stage.nativeWindow.addEventListener(KeyboardEvent.KEY_UP,keyisUp);
function keyisDown(e){
trace(e.keyCode)
if(e.keyCode == 91){
winkeyDown = true
}
if(e.keyCode == 15){
altkeyDown = true
}
if(winkeyDown && altkeyDown){
stage.nativeWindow.activate()
trace(stage.nativeWindow.x)
}
}
function keyisUp(e){
if(e.keyCode == 91){
winkeyDown = false
}
if(e.keyCode == 15){
altkeyDown = false
}
}
this only trace e.keyCode when the window is in focus.
This is obviously because of stage. but I've been searching around for hours and can only find stuff about how to force focus and text field focus and such.
what should I use for it to detect what key is down when the window isn't in focus?