How do I make 2 KeyDown functions work independently? - actionscript-3

package
{
import flash.display.MovieClip;
import flash.events.*;
public class untitledCode extends MovieClip
{
private var speed:Number = 5;
public function untitledCode()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, whenKey1);
stage.addEventListener(KeyboardEvent.KEY_DOWN, whenKey2);
}
private function whenKey1(event:KeyboardEvent):void
{
if (event.keyCode == 38)
{
mcPlayer1.y -= speed;
}
if (event.keyCode == 40)
{
mcPlayer1.y += speed;
}
if (event.keyCode == 37)
{
mcPlayer1.x -= speed;
}
if (event.keyCode == 39)
{
mcPlayer1.x += speed;
}
if (event.keyCode == 96)
{
mcPlayer1.play();
}
}
private function whenKey2(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
mcPlayer2.y -= speed;
}
if (event.keyCode == 83)
{
mcPlayer2.y += speed;
}
if (event.keyCode == 65)
{
mcPlayer2.x -= speed;
}
if (event.keyCode == 68)
{
mcPlayer2.x += speed;
}
if (event.keyCode == 90)
{
mcPlayer2.play();
}
}
}
}
There are 2 MovieClips, mcPlayer1 and mcPlayer2. When I hold a key for one MovieClip and then press a key for another, the first MovieClip stops(and vice versa). How do I make them move simultaneously.

Based on the other answer I informed you about that was already on SO, I tested their answer and although it works, there is keyboard lag with their implementation. So I optimized it using the ENTER_FRAME event...
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
private var speed:Number = 5;
private var _keyDownStatus:Object = { };
public function Main()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
stage.addEventListener(Event.ENTER_FRAME, keyCheck);
}
private function onUp(e:KeyboardEvent):void {
_keyDownStatus[e.keyCode] = false;
}
private function onDown(e:KeyboardEvent):void {
_keyDownStatus[e.keyCode] = true;
}
private function keyCheck(e:Event):void {
// Player 1 Events
if (_keyDownStatus[Keyboard.LEFT]) {
mcPlayer1.x -= speed;
}
if (_keyDownStatus[Keyboard.RIGHT]) {
mcPlayer1.x += speed;
}
if (_keyDownStatus[Keyboard.UP]) {
mcPlayer1.y -= speed;
}
if (_keyDownStatus[Keyboard.DOWN]) {
mcPlayer1.y += speed;
}
if (_keyDownStatus[Keyboard.NUMPAD_0]) {
mcPlayer1.play();
}
//Player 2 Events
if (_keyDownStatus[Keyboard.A]) {
mcPlayer2.x -= speed;
}
if (_keyDownStatus[Keyboard.D]) {
mcPlayer2.x += speed;
}
if (_keyDownStatus[Keyboard.W]) {
mcPlayer2.y -= speed;
}
if (_keyDownStatus[Keyboard.S]) {
mcPlayer2.y += speed;
}
if (_keyDownStatus[Keyboard.Z]) {
mcPlayer2.play();
}
}
}
}
I've tested this in Flash CC 2014 and it works perfectly! I did change the name of the class in my example for my example to work, so please change it to be whatever class name you need it to be.

I do recommend you do add only one key down event listener and save each pushed key and add a key up event listener to remove, so, you can control when only one key is pressed or multiple keys.
I created a simple example (just to explain the main logic), you should adapt and optimize it for your own needs.
private var keyControl:Vector.<uint>;
public function Test()
{
keyControl = new Vector.<uint>();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDownHandler, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, onUpHandler, false, 0, true);
}
private function onUpHandler(event:KeyboardEvent):void
{
keyControl.splice(keyControl.indexOf(event.keyCode), 1);
}
private function onDownHandler(event:KeyboardEvent):void
{
if(!isKeyPressed(event.keyCode)) keyControl.push(event.keyCode);
/*
to check if some key is being pressed use
if(isKeyPressed(Keyboard.SPACE))
{
// do something
}
if(isKeyPressed(Keyboard.SPACE) && isKeyPressed(Keyboard.A))
{
// do something
}
*/
}
private function isKeyPressed(key:uint):Boolean
{
var returnValue:Boolean;
for (var i:int = 0, numKeys:uint = keyControl.length; i < numKeys; i++)
{
if(keyControl[i] == key)
{
returnValue = true;
break;
}
}
return returnValue;
}

Related

Trying to add keyboard events to a child movieclip I call to the stage in code

So this is my first semester in school coding and right now I'm trying to make a little 2D game with a character who I need to move up and down.
So far, I've been able to create a titlescreen and then when you click start it goes to the next screen, where my main character is.
I add him to the stage manually through the code, and then I tried to make him move up down left and right with the arrow keys but he only appears, and does not move.
This is my code so far
package lib.fly
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class FlyGame extends MovieClip
{
public var mainCharacter:MovieClip;
public var vx:Number;
public var vy:Number;
public function FlyGame()
{
trace ("Initiate");
init();
}
private function init():void
{
vx = 0;
vy = 0;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveAround);
stage.addEventListener(KeyboardEvent.KEY_UP, dontMove);
//var dx:Number = speed* Math.cos(angle);
//var dy:Number = speed* Math.sin(angle);
trace ("Keyboard Event Listeners");
}
private function moveAround(event:KeyboardEvent):void
{
trace ("Actual Keyboard Events");
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
else if (event.keyCode == Keyboard.UP)
{
vy = - 5;
}
else if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
private function dontMove(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
else if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
vy = 0;
}
}
public function onEnterFrame(event:Event):void
{
mainCharacter = new BoyFlying();
mainCharacter.x = 20;
mainCharacter.y = 150;
mainCharacter.x += vx;
mainCharacter.y += vy;
addChild(mainCharacter);
}
}
}
The output produces the trace statements up until my "Actual Keyboard Events"
Sorry, I'm brand new to this so any help would be appreciated. Thank you for your time
Try this logic below and see if it helps your program to work as expected...
Adjust function init()
private function init():void
{
vx = vy = 0; //chain them since same value
mainCharacter = new BoyFlying(); //create once here and control in other functions
mainCharacter.x = 20;
mainCharacter.y = 150;
mainCharacter.addEventListener(Event.ENTER_FRAME, onEnterFrame);
addChild(mainCharacter);
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveAround);
//stage.addEventListener(KeyboardEvent.KEY_UP, dontMove); //what is it good for?
trace ("added... Keyboard Event Listeners");
//var dx:Number = speed* Math.cos(angle);
//var dy:Number = speed* Math.sin(angle);
}
Adjust function moveAround()
private function moveAround(event:KeyboardEvent):void
{
trace ("Actual Keyboard Events");
if (event.keyCode == Keyboard.LEFT)
{ vx -= 5; }
if (event.keyCode == Keyboard.RIGHT)
{ vx += 5; }
if (event.keyCode == Keyboard.UP)
{ vy -= 5; }
if (event.keyCode == Keyboard.DOWN)
{ vy += 5; }
}
Adjust function onEnterFrame()
public function onEnterFrame(event:Event):void
{
//# no need for += here since function moveAround() changes these vx and vy values on key press
//# infact your character could be moved (x/y) just by keyboard event instead of per FPS screen update (eg: not with EnterFrame)
mainCharacter.x = vx;
mainCharacter.y = vy;
}

How to detect if a player is on a platform

I am making a basic platform game using as3, and am trying to find a way to detect if my player is on the platform so I can allow him to jump if he is on it, but not be able to jump if he's off the platform.Here is my code:
package {
import flash.display.MovieClip
import flash.events.Event
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends MovieClip
{
var _vx = 0
var _vy = 0
var _ay = 0.5
var _isOnGround:Boolean
var canJump:Boolean
var _collisionArea:MovieClip
// Constants:
// Public Properties:
// Private Properties:
// Initialization:
public function Main()
{
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp)
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
_vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
_vx = 5;
}
else if (event.keyCode == Keyboard.UP )
{
if (canJump)
{
_vy = -10
}
}
}
function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
_vx = 0;
}
else if (event.keyCode == Keyboard.RIGHT)
{
_vx = 0;
}
}
public function onEnterFrame(event:Event):void
{
if(player1.isOnGround)
{
canJump=true
}
else if (!player1.isOnGround)
{
canJump=false
}
if (_vy > 10)
{
_vy = 10
}
player1.y += _vy
player1.x += _vx
vy += _ay
//Player vs wall collision
for (var i:int = 0; i <= 4; i++)
{
CollisionB.platform_BlockRectangles(player1, this["wall" + i]);
//trace("wall" + i);
}
}
public function set vx(vxValue:Number):void
{
_vx = vxValue;
}
public function get vx():Number
{
return _vx;
}
public function set vy(vyValue:Number):void
{
_vy = vyValue;
}
public function get vy():Number
{
return _vy;
}
public function get isOnGround():Boolean
{
return _isOnGround;
}
public function set isOnGround(onGround:Boolean):void
{
_isOnGround = onGround;
}
public function get collisionArea():MovieClip
{
return _collisionArea;
}
}
}
Im also using another class where the code is:
static public function platform_BlockRectangles(objectA:Object,objectB:Object):void
{
//This function requires the following setter properties in objectA:
// _objectIsOnGround:Boolean, vx:Number, vy:Number
var objectA_Halfwidth=objectA.width/2;
var objectA_Halfheight=objectA.height/2;
var objectB_Halfwidth=objectB.width/2;
var objectB_Halfheight=objectB.height/2;
var dx=objectB.x-objectA.x;
var ox=objectB_Halfwidth+objectA_Halfwidth-Math.abs(dx);
if (0<ox)
{
var dy=objectA.y-objectB.y;
var oy=objectB_Halfheight+objectA_Halfheight-Math.abs(dy);
if (0<oy)
{
if (ox<oy)
{
if (dx<0)
{
ox*=-1;
oy=0;
}
else
{
oy=0;
}
//Dampen horizontal velocity
objectA.vx=0;
}
else
{
if (dy<0)
{
ox=0;
oy*=-1;
objectA.isOnGround=true;
}
else
{
ox=0
}
//Dampen vertical velocity
objectA.vy=0;
}
objectA.x-=ox;
objectA.y+=oy;
}
}
}
Someone please help!!!!!!!
I extremely recommend you to use some library like: Flixel, Citrus
Try to follow this tutorial, will explain all necessary logic to help you with your game
You can use AABB collision detection. Here is a tutorial (the Distance function part).
If you google the term you will get a lot of info in the subject.
But i recomend you to use flixel or flashPunk is you are just starting and want to do games, they take care of these stuff for you and you can get to just make the game.

AS3 error 1084 syntax error expecting rightparen before dot

i am new to this whole as3 thing and i am struggling immensely. I have been sat for the last two days trying to do something i can imaging to be simple to everyone else reading this. I am trying to create a game where i have a skate boarder controlled by the keyboard keys. However when i type this code in i am getting a 1084 error please help before i throw my laptop out the window. Thanks!!
package {
import flash.display.*;
import flash.events.*;enter code here
public class skatefate extends MovieClip {
var the_skater:Sprite = new Sprite();
the_skater.addChild:(skater);
var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var moveDown:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
stage.addEventListener(Event.ENTER_FRAME, moveskater);
function keyPressedDown(event:KeyboardEvent) {
if (event.keyCode == 37) {
moveLeft = true;
} else if (event.keyCode == 39) {
moveRight = true;
} else if (event.keyCode == 65) {
moveUp = true;
} else if (event.keyCode == 90) {
moveDown = true;
}
}
function keyPressedUp(event:KeyboardEvent) {
if (event.keyCode == 37) {
moveLeft = false;
} else if (event.keyCode == 39) {
moveRight = false;
} else if (event.keyCode == 65) {
moveUp = false;
} else if (event.keyCode == 90) {
moveDown = false;
}
}
function moveskater(event:Event) {
var speed:uint = 20;
if (moveLeft) {
skater.x -= speed;
if (skater.x < 0){
skater.x = 800;
}
}
}
if (moveRight) {
skater.x += speed;
if (skater.x > 800){
skater.x = 0;
}
}
if (moveUp) {
skater.y -= speed;
if (skater.y > 0){
skater.y = 0;
}
}
if (moveDown) {
skater.y += speed;
if (skater.y > 0){
skater.y = 0;
}
}
I tried your code but didn't get your error. Your sample throws other errors & problems.
So my advice is these two things..
The correct to construct your code...
package
{
//IMPORTS go here
//Declare your Class
public class skatefate extends MovieClip
{
//VARS go here
//*******************************************************************
//note: later you may also add other VARS inside functions as needed
//(but were not originally put (declared) in this section)
//*******************************************************************
//Declare main function of your Class (must have same name as Class (.as)
public function skatefate()
{
//Constructor code here
//************************************************************************
// Your main program code and related functions (K/board etc) go here and
// will reference your VARS declared above in public Class construction)
//************************************************************************
} //End of (public) Function
} //End of (public) Class
} //End of Package
Just incase you still struggle, this edit of your code shown should compile. From there you can study & learn. Hopefully one more laptop will survive in this cruel world.
package
{
import flash.display.*;
import flash.events.*; //enter code here
//Declare your Class
public class skatefate extends MovieClip {
var the_skater:Sprite = new Sprite();
var skater:Sprite = new Sprite(); //hide line if skater exists already (i.e in Library)
var speed:uint = 20;
//Declare main function of your Class
public function skatefate ()
{
var moveLeft:Boolean = false;
var moveRight:Boolean = false;
var moveUp:Boolean = false;
var moveDown:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
stage.addEventListener(Event.ENTER_FRAME, moveskater);
the_skater.addChild(skater);
addChild(the_skater); //adds to stage
function keyPressedDown (event:KeyboardEvent)
{
if (event.keyCode == 37) { moveLeft = true; }
else if (event.keyCode == 39) { moveRight = true; }
else if (event.keyCode == 65) { moveUp = true; }
else if (event.keyCode == 90) { moveDown = true; }
}
function keyPressedUp (event:KeyboardEvent)
{
if (event.keyCode == 37) { moveLeft = false; }
else if (event.keyCode == 39) { moveRight = false; }
else if (event.keyCode == 65) { moveUp = false; }
else if (event.keyCode == 90) { moveDown = false; }
}
function moveskater(event:Event)
{
//var speed:uint = 20; //already declared at top
//speed = 20; // later change 'speed' this way by updating number
if (moveLeft) {
skater.x -= speed;
if (skater.x < 0)
{ skater.x = 800; }
}
if (moveRight) {
skater.x += speed;
if (skater.x > 800)
{ skater.x = 0; }
}
if (moveUp) {
skater.y -= speed;
if (skater.y > 0)
{ skater.y = 0; }
}
if (moveDown) { skater.y += speed;
if (skater.y > 0)
{ skater.y = 0; }
}
} //close 'moveskater' function
} //End of your (public) Function
} //End of your (public) Class
} //End of Package
Hope it helps. Ask for advice in the comments and don't forget to tick as "correct answer" if it works for you. That's how we say "Thanks" on Stack Overflow.

Undefined hitTestPoint error

When I have this code, it comes up with this error "1061: Call to a possibly undefined method hitTestPoint through a reference with static type Class."
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;
public class Code extends MovieClip {
var charSpeed:int = 0;
var velocity:int = 0;
var gravity:Number = 1;
var Jump:Boolean = false;
public function startGame(){
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
stage.addEventListener(Event.ENTER_FRAME, loop);
}
public function Code() {
// constructor code
}
function checkKeyDown(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.LEFT){
charSpeed -= 10;
}
if (evt.keyCode == Keyboard.RIGHT){
charSpeed += 10;
}
if (evt.keyCode == Keyboard.DOWN){
if(!Jump){
velocity -= 14;
Jump = true;
}
}
}
function checkKeyUp(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.LEFT){
charSpeed = 0;
}
if (evt.keyCode == Keyboard.RIGHT){
charSpeed = 0;
}
}
function loop(evt:Event){
player.x = velocity;
if (player.x < 0){
player.x = 0;
}
if (player.x > 550){
player.x = 550;
}
velocity += gravity;
if (!platform.hitTestPoint(player.x, player.y, true)){
player.y += velocity;
}
for (var i = 0; i < 10; i++){
if (platform.hitTestPoint(player.x, player.y, true)){
player.y--;
velocity = 0;
Jump = false;
}
}
}
}
}
The option I had was adding a MovieClip variable to my platform, and that did remove this error, but I wasn't sure how to link my actual instance of platform to my variable. Oh and by the way the platform's instance is platform. If anyone has any clues on how to fix this error, that would be great.
You may set platform value in the constructor
public function class Code {
//assume Platform is the class type,remember to import it
private var platform:Platform;
public function Code(value:Platform) {
platform = value;
}
}
When you create Code instance
var code:Code = new Code(platform);//platform is the instance

Actionscript 3 returns Error #1009

I am creating a shooting game. I have encountered a problem with my code when I decided to create a method to remove the missile after reaching the top of the stage. I can run the program without any issues only I have realize that the missile was not remove away from the stage, if I hold the shooting button. However, if I tap the shooting button, the missile will removed away with this error #1009 printing out of the output.
Is there any solution to fix the problem?
Here's is the error after the missile flew to the top of the stage with debugging enabled:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Missle/destroyMissle()[E:\Experiment\ExperimentProject\Missle.as:39]
at main/checkMissleOffScreen()[E:\Experiment\ExperimentProject\main.as:63]
at main/eventUpdated()[E:\Experiment\ExperimentProject\main.as:51]
Here's the main's class:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
/**
* ...
* #author test
*/
public class main extends MovieClip
{
//Objects
public var rect:MovieClip;
public var missle:Missle;
//Array
private var missleArray:Array;
//Keyboard section
var leftKeyIsDown:Boolean;
var rightKeyIsDown:Boolean;
var upKeyIsDown:Boolean;
var downKeyIsDown:Boolean;
var spaceKeyIsDown:Boolean;
//Speed
var characterSpeed:Number = 15;
//Main constructor
public function main()
{
//Array initializer
missleArray = new Array();
missle = new Missle();
//Update events listeners.
stage.addEventListener(Event.ENTER_FRAME, eventUpdated);
//Update keyboard events listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUnpressed);
}
//Events functions
//This functions updated everytime the object is move
private function eventUpdated(e:Event):void
{
playerMoving();
playerClampMoving();
checkMissleOffScreen();
}
private function checkMissleOffScreen():void
{
for (var i = 0; i < missleArray.length; i++ )
{
var currentMissle:Missle = missleArray[i];
if (currentMissle.y < 0)
{
missleArray.splice(i, 1);
missle.destroyMissle();
}
}
}
private function playerClampMoving():void
{
if (rect.x < 0)
{
rect.x = 0;
}
if (rect.x > stage.stageWidth - rect.width)
{
rect.x = stage.stageWidth - rect.width;
}
if (rect.y < 0)
{
rect.y = 0;
}
if (rect.y > stage.stageHeight - rect.height)
{
rect.y = stage.stageHeight - rect.height;
}
}
private function playerMoving():void
{
if (leftKeyIsDown == true)
{
rect.x -= characterSpeed;
}
if (rightKeyIsDown == true)
{
rect.x += characterSpeed;
}
if (upKeyIsDown == true)
{
rect.y -= characterSpeed;
}
if (downKeyIsDown == true)
{
rect.y += characterSpeed;
}
if (spaceKeyIsDown == true)
{
shootingMissle();
}
}
private function shootingMissle():void
{
missle = new Missle();
missle.x = rect.x + (rect.width / 2);
missle.y = rect.y;
missleArray.push(missle);
trace(missleArray.length);
stage.addChild(missle);
}
//Keyboard functions
//Check to see whether the user releases the keyboard
private function keyUnpressed(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
leftKeyIsDown = false;
}
if (e.keyCode == 39)
{
rightKeyIsDown = false;
}
if (e.keyCode == 40)
{
downKeyIsDown = false;
}
if (e.keyCode == 38)
{
upKeyIsDown = false;
}
if (e.keyCode == 32)
{
spaceKeyIsDown = false;
}
}
//Check to see whether the user presses the keyboard
private function keyPressed(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
leftKeyIsDown = true;
}
if (e.keyCode == 39)
{
rightKeyIsDown = true;
}
if (e.keyCode == 40)
{
downKeyIsDown = true;
}
if (e.keyCode == 38)
{
upKeyIsDown = true;
}
if (e.keyCode == 32)
{
spaceKeyIsDown = true;
}
}
}
}
Here's the Missle's Class:
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author test
*/
public class Missle extends Sprite
{
public function Missle()
{
addEventListener(Event.ADDED_TO_STAGE, onAdd);
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
//Objects are on the stage
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, missleLaunch);
}
private function missleLaunch(e:Event):void
{
this.y -= 15;
}
public function destroyMissle():void
{
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, missleLaunch);
}
}
}
Try this:
public function destroyMissle():void
{
if(parent !== null) parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME, missleLaunch);
}
It is a possibility that you were calling .destroyMissile() more than once meaning parent would be null because you've removed it from the stage and it has no parent.