AS3 keyboard animated character - Compiler errors all over the place despite following tutorial to the letter - actionscript-3

Trying to create a 2D character that responds to keyboard inputs in Flash Professional CC. Every YouTube tutorial my son and I have tried produces Compiler errors and NOTHING works.
import flash.events.KeyboardEvent;
import flash.events.Event;
var rightKeyIsDown:Boolean = false;
var leftKeyIsDown:Boolean = false;
var upKeyIsDown:Boolean = false;
var downKeyIsDown:Boolean = false;
var playerSpeed:int = 7;
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressAKey);
stage.addEventListener(KeyboardEvent.KEY_UP, releaseAKey);
function pressAKey(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
rightKeyIsDown = true;
}
if(event.keyCode == Keyboard.LEFT)
{
leftKeyIsDown = true;
}
if(event.keyCode == Keyboard.UP)
{
upKeyIsDown = true;
}
if(event.keyCode == Keyboard.DOWN)
{
downKeyIsDown = true;
}
}
function releaseAKey(event.KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
rightKeyIsDown = false;
}
if(event.keyCode == Keyboard.LEFT)
{
leftKeyIsDown = false;
}
if(event.keyCode == Keyboard.UP)
{
upKeyIsDown = false;
}
if(event.keyCode == Keyboard.DOWN)
{
downKeyIsDown = false;
}
}
player_mc.addEventListener(Event.ENTER_FRAME, moveThePlayer);
function moveThePlayer(event:Event):void
{
if(rightKeyIsDown == true)
{
player_mc.x += playerSpeed;
}
if(leftKeyIsDown == true)
{
player_mc.x -+ playerSpeed;
}
}
What is wrong with the above code? We have followed this tutorial, which seems very straightforward however the minute we type in a curly bracket it highlights in red, and then when we try to test we receive Compiler Errors.
Scene 1, Layer 'Player', Frame 1, Line 35, Column 27 1084: Syntax error: expecting rightparen before dot.
We are using Flash Professional CC and AS3 - is there a better resource for tutorials for this type of thing as we're being driven mad having tried at least 5 of these now without success.
Would really appreciate some advice on why the above is wrong and also where we might find tutorials that actually work!
Thank you.
NJ & Son! :)

I threw your code into Flash and did not see any issues surrounding mismatching parenthesis; however, I did notice the following errors
First, In the following if control structure:
if(leftKeyIsDown == true)
{
player_mc.x -+ playerSpeed;
}
You are attempting to use an operator of -+ but no such operator exists in Flash ActionScript. I'm thinking you meant to do the following instead:
if(leftKeyIsDown == true)
{
player_mc.x -= playerSpeed;
}
Second, the issue is right here:
function releaseAKey(event.KeyboardEvent):void
{
// your code
}
You need a : to specify the datatype. Can't believe I missed that. So it should be:
function releaseAKey(event:KeyboardEvent):void
{
// your code
}
I was able to plug this code into Flash CC and get it to compile with no errors. Cheers!

Related

EventListener for key combinations in AS3?

im tryin to figure out condition AND for "shortcut" for quitting standalone app from flash. I would like to push 2 keys and combination of these two keys "C+M" should quit my app.
Heres my code but its still not working. I tryed to make shure that app allow me to push multiple buttons at the same time and after that I created the function for quitting.
Any answers be great.
var keyPressedC:Boolean;
var keyPressedM:Boolean;
addEventListener(KeyboardEvent.KEY_DOWN, check_key_down,false,0,true);
addEventListener(KeyboardEvent.KEY_UP, check_key_up,false,0,true);
addEventListener(Event.ENTER_FRAME, check_keys,false,0,true);
function check_keys(event:Event):void
{
if(keyPressedC)
trace("pushed C")
if(keyPressedM)
trace("pushed M")
}
function check_key_down(event:KeyboardEvent):void
{
if(event.keyCode == 67)
keyPressedC = true;
if(event.keyCode == 77)
keyPressedM = true;
}
function check_key_up(event:KeyboardEvent):void
{
if(event.keyCode == 67)
keyPressedC = false;
if(event.keyCode == 77)
keyPressedM = false;
}
import flash.system.fscommand;
stage.addEventListener(KeyboardEvent.KEY_DOWN, enterKeyHandlercm);
function enterKeyHandlercm(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.C && event.keyCode == Keyboard.M)
{
fscommand("quit");
}
}
Edited, still not working:
var keyPressedC:Boolean;
var keyPressedM:Boolean;
addEventListener(KeyboardEvent.KEY_DOWN, check_key_down,false,0,true);
addEventListener(KeyboardEvent.KEY_UP, check_key_up,false,0,true);
addEventListener(Event.ENTER_FRAME, check_keys,false,0,true);
function check_keys(event:Event):void
{
if(keyPressedC)
trace("pushed C")
if(keyPressedM)
trace("pushed M")
}
function check_key_down(event:KeyboardEvent):void
{
if(event.keyCode == 67)
keyPressedC = true;
if(event.keyCode == 77)
keyPressedM = true;
}
function check_key_up(event:KeyboardEvent):void
{
if(event.keyCode == 67)
keyPressedC = false;
if(event.keyCode == 77)
keyPressedM = false;
}
import flash.system.fscommand;
stage.addEventListener(KeyboardEvent.KEY_DOWN, enterKeyHandlercm);
function enterKeyHandlercm(event:KeyboardEvent):void
{
if (keyPressedM == true && keyPressedC == true)
{
fscommand("quit");
}
}
In your enterKeyHandlercm block, your logic should be evaluating the keypressed value, not the keyCode value.
function enterKeyHandlercm(event:KeyboardEvent):void
{
if (keyPressedM == true && keyPressedC == true)
{
fscommand("quit");
}
}
With this code, a different MC is added for each of your 5 key possibilities (c up, c down , m up, m down, c+m down).
package {
import flash.display.*;
import flash.events.*;
import flash.system.fscommand;
import flash.system.System; //add this if you try System.exit(0);
public class FlashTest extends MovieClip
{
public function FlashTest()
{
var keyPressedC:Boolean;
var keyPressedM:Boolean;
// need to add eventListener to stage
// default values work fine.
stage.addEventListener(KeyboardEvent.KEY_DOWN, check_key_down);
stage.addEventListener(KeyboardEvent.KEY_UP, check_key_up);
stage.addEventListener(Event.ENTER_FRAME, check_keys);
function check_key_down(event:KeyboardEvent):void
{
if(event.keyCode == 67)
{
keyPressedC = true;
newBall(-100);
}
if(event.keyCode == 77)
{
keyPressedM = true;
newBall();
}
}
function check_key_up(event:KeyboardEvent):void
{
if(event.keyCode == 67)
{
keyPressedC = false;
newBall(-50);
}
if(event.keyCode == 77)
{
keyPressedM = false;
newBall(50);
}
}
function enterKeyHandlercm(event:KeyboardEvent):void
{
if (keyPressedM == true && keyPressedC == true)
{
newBall(100);
fscommand("quit");
// or try System.exit(0);
}
}
function newBall(x:Number=0):void
{
var ball:Sprite = new Sprite();
ball.graphics.lineStyle();
ball.graphics.beginFill(0x000000);
ball.graphics.drawCircle(0,0,20);
ball.graphics.endFill();
addChild(ball);
ball.x = stage.stageWidth/2+x;
ball.y = stage.stageHeight/2;
}
}
}
}
Please forgive my verbosity, but this way we aren't missing anything. The reason I added the ball constructor was because I only have my laptop with me so I had to use an online IDE and I don't know how to find an output window or run a debugger and it doesn't take system commands. But what I can confirm with the ball method is that when "c" and "m" are pressed together, a unique MC is instantiated. This means our code now causes flash to register a unique event when both keys are simultaneously pressed.

Why does flash output a TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/addChild()

This is my code that I have so far
package {
import flash.display.MovieClip;
import flash.events.*;
public class Main extends MovieClip {
var leftpressed:Boolean = false;
var rightpressed:Boolean = false;
public function Main()
{
//constructor code
Spaceship.addEventListener(Event.ENTER_FRAME, moveToKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, setKeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP, setKeyUnpress);
stage.addEventListener(KeyboardEvent.KEY_DOWN, FlyBullet);
}
function moveToKey (event:Event)
{
if (leftpressed && (Spaceship.x>0))
{
Spaceship.x = -5;
}
if (rightpressed && (Spaceship.x<550))
{
Spaceship.x = +5;
}
}
function setKeyPress(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
leftpressed = true;
}
if (e.keyCode == 39)
{
rightpressed = true;
}
}
function setKeyUnpress(e:KeyboardEvent): void
{
if (e.keyCode == 37)
{
leftpressed = false;
}
if (e.keyCode == 39)
{
rightpressed = false;
}
}
function FlyBullet (e:KeyboardEvent):void
{
if (e.keyCode == 32)
var bulletshot:Bullet = new Bullet();
addChild(bulletshot);
bulletshot.x = Spaceship.x;
bulletshot.y = Spaceship.y
}
}
}
With the biggest issue with the final FlyBullet function that outputs an the error listed as
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at Main/FlyBullet()
This is your problem:
if (e.keyCode == 32)
var bulletshot:Bullet = new Bullet();
addChild(bulletshot);
bulletshot.x = Spaceship.x;
bulletshot.y = Spaceship.y
There are no curly brackets so the if condition only applies to the first line where bulletshot is assigned. In other words, if you press any key other than SPACE it will skip the assignment of bulletshot but still try to addChild(bulletshot), but since bulletshot was not assigned a value it is null and you get errors.
I think you meant this:
if (e.keyCode == Keyboard.SPACE) {
var bulletshot:Bullet = new Bullet();
addChild(bulletshot);
bulletshot.x = Spaceship.x;
bulletshot.y = Spaceship.y
}
PS: Your code is poorly indented in a lot of places. It helps to have correctly indented code. An auto-formatter could help you here.
It is generally considered bad practice to omit brackets in multiline if statements, this is an example why. Whenever e.keyCode != 32 the addChild line will try to run.
Solution would be:
///...in the Main function//
stage.addEventListener(KeyboardEvent.KEY_DOWN, flyBullet);
///...
function flyBullet (e:KeyboardEvent):void
{
if (e.keyCode == 32)
{
var bulletshot:Bullet = new Bullet();
addChild(bulletshot);
bulletshot.x = Spaceship.x;
bulletshot.y = Spaceship.y;
}
}
Some unrelated as3 code quality tips, to avoid possible errors later:
I'm guessing Spaceship isn't a static class, so i suggest using lowercase first letters for variable/function names, and uppercase for classes, but this is just good practice and does not affect your codes correctness.
It is also good practice to define the accessibility of your functions, i.e public, private, internal, protected. If you omit it the default is internal.
And only skip brackets after conditionals when necessary.

Actionscript 3.0: Cannot get key input

guys. I created a little game. Nothing actually happening thought, because im not getting my keyboard input. I spend some time trying to create my own taht didnt work. Then I copy/pasted code from official actionscript 3.0 reference page, but tweaked it for my game (but I didnt touch anything related to keyboard stuff). Also the only thing my game returns in cosnole is false
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
stop();
var left = false;
var right = false;
var speed = 0.3;
player.addEventListener(KeyboardEvent.KEY_DOWN, keydF);
player.addEventListener(KeyboardEvent.KEY_UP, keyuF);
player.addEventListener(Event.ENTER_FRAME, updF);
function keydF(event:KeyboardEvent):void {
trace("test0");
if(event.keyCode == Keyboard.D) {
trace("test1");
left = true;
}
if(event.keyCode == Keyboard.A) {
right = true;
}
}
function keyuF(event:KeyboardEvent):void {
trace("test2");
if(event.keyCode == Keyboard.D) {
left = false;
}
if(event.keyCode == Keyboard.A) {
right = false;
}
}
function updF(e:Event):void {
if(left) {
level.x -= speed;
}
if(right) {
level.x += speed;
}
trace(left + ""); //always false :\
}
If you want to get the key input to your app, you should add the listeners to the stage :)

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;
}
}

How to do you get an character to jump?

This is my fist time ever needing to use this for one of my games. I want to have the character jump. I have been trying to get this result for about an hour, but with no luck =( I am using AS3, and flash CS5.5. So far all my code does is make the character go left, and right based on keyboard input. Could someone please help?
Here is my code so far:
public class Dodgeball extends MovieClip
{
public var character:Character;
public var rightDown:Boolean = false;
public var leftDown:Boolean = false;
public var speed:Number = 3;
public var timer:Timer;
public function Dodgeball()
{
character= new Character();
addChild(character);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, MyKeyUp);
timer = new Timer(24);
timer.addEventListener(TimerEvent.TIMER, moveClip);
timer.start();
}
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.RIGHT)
{
rightDown = true;
if(character.currentLabel != "walkingRight")
{
character.gotoAndStop ("walkingRight");
}
}
if (event.keyCode == Keyboard.LEFT)
{
leftDown = true;
if (character.currentLabel != "backingUp")
{
character.gotoAndStop("backingUp");
}
}
}
public function MyKeyUp(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
character.gotoAndStop("standing");
rightDown = false;
}
if (event.keyCode == Keyboard.LEFT)
{
character.gotoAndStop("standingLeft");
leftDown = false;
}
}
public function moveClip(event:TimerEvent):void
{
if (rightDown)
{
character.x += speed;
}
if (leftDown)
{
character.x -=speed;
}
event.updateAfterEvent();
}
}
}
One method you can try is found here: http://www.actionscript.org/forums/showthread.php3?t=256009 Like your speed variable, grav determines the vertical position of the character.
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onKeyDown(evt:KeyboardEvent):void
{
if(evt.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(evt:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
}
Edit: Jason's method is fine, but I'm not sure if it would be useful if you plan to have some kind of collision detection.
What I would do is create a motion tween of the character jumping. then call gotoAndPlay on that frame, and on the last frame of the tween put a stop, or a gotoAndStop on the "stationary" frame, or whatever frame represents a neutral position.
if (event.keyCode == Keyboard.SHIFT)
{
character.gotoAndPlay("simpleJump");
jumpDown = false;
}
This will give you the greatest animation control over the look and feel. You could also do it programmatically, but personally, I recommend against it. It will take less time to set it up, and you can tweak and refine the jump animations later. You could make several types of jump animations based on object near the target etc.
I would also change this stuff:
if(character.currentLabel != "walkingRight")
By defining a new function where you have all the rules for when and where something can be done, so that in your control logic, you just call
if(characterCan(character,"walkright")) ...
Where characterCan(String) is a method that check if this is possible. For instance, if you are jumping and shooting, you obviously cannot walk right, so in the end, you will have to start adding pieces of logic into those if statements and it's gonna become a cluttered mess.
A very simple approach is to have a vertical speed as well as a horizontal speed.
When the user presses "UP" or "JUMP", set y speed to a negative value and update it in your movieClip function. When the character gets to a certain height, reverse the speed.
Using gravity and acceleration looks better but this is a really good place to start. Look into kinematic equations to see how you would make the character accelerate.
public var originalY;
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.UP && vSpeed == 0)
{
originalY = character.y;
ySpeed = -1;
}
}
public function moveClip(event:TimerEvent):void
{
if (vSpeed != 0)
{
character.y += vSpeed;
/* make the character fall down after reaching max jump height */
if(originalY - character.y > jumpHeight) {
vSpeed = vSpeed * -1;
}
/* level the character after he's hit the ground (so he doesn't go through) */
else if(character.y >= originalY) {
character.y = originalY;
vSpeed = 0;
}
}
}