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

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

Related

how do I make the bullet move Actionscript 3.0

I am making a very simpel flash game to understand AS3. I have made a cirkel with controls. When I press the space I want to fire a bullet. I have tried for, while loops and different tutorials but I just can't figure out how to do this.
This is m code:
import flash.net.drm.LoadVoucherSetting;
//controls
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
var dir:String = "default";
function reportKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
ball_mc.x -= 10;
dir = "venstre";
}
if (event.keyCode == Keyboard.RIGHT)
{
ball_mc.x += 10;
dir = "hojre";
}
if (event.keyCode == Keyboard.UP)
{
ball_mc.y -= 10;
dir = "op";
}
if (event.keyCode == Keyboard.DOWN)
{
ball_mc.y += 10;
dir = "ned";
}
if (event.keyCode == Keyboard.SPACE)
{
shootBullet();
}
}
var speed1:int = 1;
function shootBullet():void
{
//instantiate your object
var bullet:Bullets = new Bullets ;
//add it to the stage
addChild(bullet);
//object will default to x=0 , y=0 so you can define that as well
bullet.x = ball_mc.x;
bullet.y = ball_mc.y +(ball_mc.width/2);
bullet.y += 10 * 2;
}
stop();
To make it move you need to use some event that happens repeatedly with some interval.
A Timer:
var myTimer:Timer = new Timer(25);//interval, milliseconds
myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
myTimer.start();
var speedX:int = 0;
var speedY:int = 1;
function timerHandler(event:TimerEvent):void {
bullet.y += speedX;
bullet.x += speedY;
}
Or an ENTER_FRAME event:
addEventListener(Event.ENTER_FRAME, onFrame);
function onFrame(event:Event):void {
bullet.y += speedX;
bullet.x += speedY;
}

Collision code stops working after adding to stage

So I'm using actionscript 3, and my collision code stops working after adding it to stage with code. the player just cant move at all when touching the wall. However if I add it to stage by dragging the movieclip to the stage, it works fine, the player doesn't freeze when touching the wall, instead it cant pass the wall but it can move back from it.
this is my code that adds it to stage.
public class Main extends MovieClip
{
var mountains: Mountains;
var homePage: HomePage;
var oneManager: OneManager;
public function Main()
{
mountains = new Mountains;
homePage = new HomePage;
oneManager = new OneManager;
addChild(homePage);
stage.displayState = "fullScreen";
homePage.playButtons.addEventListener(MouseEvent.CLICK, onPlayButtonsClick);
}
function onPlayButtonsClick(event:MouseEvent):void
{
stage.focus = stage;
parent.addChild(oneManager);
homePage.parent.removeChild(homePage);
}
}
this is my code that uses the collision detection to stop the player from crossing the wall
private function onKeyDown(event: KeyboardEvent): void
{
if (event.keyCode == Keyboard.A)
{
vx = -5;
}
else if (event.keyCode == Keyboard.D)
{
vx = 5;
}
else if (event.keyCode == Keyboard.W)
{
vy = -5;
}
else if (event.keyCode == Keyboard.S)
{
vy = 5;
}
}
private function onKeyUp(event: KeyboardEvent): void
{
if (event.keyCode == Keyboard.A || event.keyCode == Keyboard.D)
{
vx = 0;
}
else if (event.keyCode == Keyboard.S || event.keyCode == Keyboard.W)
{
vy = 0;
}
}
private function onEnterFrame(event: Event): void
{
if (player.collisionArea.hitTestObject(wall))
{
player.y -= vy;
}
}

Simultaneous keypress causing unwanted behaviour

I am making a shooter game with action script 3. I have a hero which moves when any of the arrow key is pressed
my code is as following
//some class level variables
private var vx :int = 0;
private var vy :int = 0;
//in the Main constructor
stage.addEventListener(KeyboardEvent.KEY_DOWN , moveHero);
stage.addEventListener(KeyboardEvent.KEY_UP , stopHero);
stage.addEventListener(Event.ENTER_FRAME , onEnter);
//and all the handlers
function moveHero(e:KeyboardEvent)
{
if (e.keyCode == 37)
{
vx = -5;
}
else if (e.keyCode == 38)
{
vy = -10;
}
else if (e.keyCode == 39)
{
vx = 5;
}
else if (e.keyCode == 40)
{
vy = 10;
}
}
function stopHero(e:KeyboardEvent)
{
//when key is up stop miving the hero
vx = 0;
vy = 0;
}
function onEnter(e:Event):void
{
//updtae hero position
hero.x += vx;
hero.y += vy;
}
Now my problem is when user have both up and down keys or left and right keys under his fingers and suddenly press them alternately then the hero shows a notable lag in making response to the key presses
You'll have to do exactly like BotMaster said in the comments, and here's how it looks like in AS3 code:
var keys:Array = new Array(255);
stage.addEventListener(KeyboardEvent.KEY_DOWN , keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP , keyUp);
stage.addEventListener(Event.ENTER_FRAME , loop);
function keyDown(e:KeyboardEvent):void {
keys[e.keyCode] = true;
}
function keyUp(e:KeyboardEvent):void {
keys[e.keyCode] = false;
}
function loop(e:Event):void {
if(keys[Keyboard.LEFT]) {
trace("Moving left...");
} else if(keys[Keyboard.RIGHT]) {
trace("Moving right...");
}
}

Null object error; cannot access it - AS3

I'm making a platform game. Im trying just to get the player to move around on the stage, and to be able to jump, with some type of gravity added to it. However, when I run it, I get this error: Error #1009: Cannot access a property or method of a null object reference.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.ui.Keyboard;
public class Code1 extends MovieClip {
var charSpeed:int = 0;
var velocity:int = 0;
var gravity:Number = 1;
var Jump:Boolean = false;
var leftKey:Boolean;
var rightKey:Boolean;
var upKey:Boolean;
private var platform:Platform;
public function startGame(){
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
stage.addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(Event.ENTER_FRAME, update);
}
public function Code() {
}
public function update(evt:Event){
moveChar();
}
public function moveChar(){
if (leftKey == true){
charSpeed -= 10;
}
if (rightKey == true){
charSpeed += 10;
}
if (upKey == true){
if(!Jump){
velocity -= 14;
Jump = true;
}
}
}
function checkKeyDown(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.UP){
upKey = true;
}
else if (evt.keyCode == Keyboard.RIGHT){
rightKey = true;
}
else if (evt.keyCode == Keyboard.LEFT){
leftKey = true;
}
}
function checkKeyUp(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.UP){
upKey = false;
}
else if (evt.keyCode == Keyboard.RIGHT){
rightKey = false;
}
else if (evt.keyCode == Keyboard.LEFT){
leftKey = false;
}
}
function loop(evt:Event){
player.x = charSpeed;
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;
}
}
}
}
}
My platform linkage is "Platform", but i set up a variable for it (or tried to). I debugged the code, and it came up with this line: player.x = charSpeed;
I have no idea what to do, if someone could help, that would be great.
You never declare or instantiate (ie player = new Player()) your player.
Alternatively, if your player is on the stage of your .fla timeline, it will need the instance name 'player'. That can be set in the object properties.
You player object is null.
I don't see the istantiation line as:
var player:Player = new Player();
Add it before use a property of your player

Character Jump with Animation

Im trying to create a platform game but im struggling with the jump part of the game. I have got the jump working but when I try to add the animation it goes all wrong. When I hit the jump button it jumps but when i lands it gets stuck on the end of the jump animation until i move. Secondly when i jump and press the right or left button it jumps but plays the run animation while i try to move in mid air. How can i resolve these problems
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Player extends MovieClip
{
//Player run speed setting
var RunSpeed:Number = 8;
//Player key presses
var RightKeyPress:Boolean = false;
var LeftKeyPress:Boolean = false;
var UpKeyPress:Boolean = false;
//Jump variables
var Gravity:Number = 1.5;
var Yvelocity:Number = 0;
var CanJump:Boolean = false;
public function Player()
{
// constructor code
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);
addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyReleased);
}
function KeyPressed(event:KeyboardEvent)
{
//When Key is Down
if (event.keyCode == 39)
{
RightKeyPress = true;
}
if (event.keyCode == 37)
{
LeftKeyPress = true;
}
if (event.keyCode == 38)
{
UpKeyPress = true;
}
}
function Update(event:Event)
{
//Adding gravity to the game world
Yvelocity += Gravity;
//if player is more than 300 on the y-axis
if (this.y > 300)
{
//Player stays on the ground and can jump
Yvelocity = 0;
CanJump = true;
}
if ((RightKeyPress == true))
{
x += RunSpeed;
gotoAndStop('Run');
scaleX = 1;
}
else if ((LeftKeyPress == true))
{
x -= RunSpeed;
gotoAndStop('Run');
scaleX = -1;
}
if ((UpKeyPress == true && CanJump))
{
Yvelocity = -15;
CanJump = false;
gotoAndStop('Jump');
}
this.y += Yvelocity;
}
function KeyReleased(event:KeyboardEvent)
{
if (event.keyCode == 39)
{
event.keyCode = 0;
RightKeyPress = false;
gotoAndStop('Idle');
}
if (event.keyCode == 37)
{
event.keyCode = 0;
LeftKeyPress = false;
gotoAndStop('Idle');
}
if (event.keyCode == 38)
{
event.keyCode = 0;
UpKeyPress = false;
}
}
}
}
this.y > 300, that is your jump end logic. Add a gotoAndStop('Idle'); in that if's block.
Just Check if canJump is true on your left and right keypresses before executing those blocks. If canJump is true allow the running stuff