Implicit coercion of a value of type flash.events:KeyboardEvent to an unrelated type flash.events:MouseEvent - actionscript-3

how can I call a function of flash events : MouseEvent in flash events keyboardEvent function
I am a biggner in as3 please help
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(event:KeyboardEvent){
if (event.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
**startFun(event);**
}
else if (keyMode == 1)
{
**checkfun(event);**
}
else if (keyMode == 2)
{
keyMode = 1;
**anotherPro(event);**
}
}
}

There is several ways, dispatch events, etc. I'll give you a simple example:
// or should be KEY_UP?
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedHandler, false, 0, true);
stage.addEventListener(MouseEvent.CLICK, exampleMouseClickHandler, false, 0, true);
function exampleMouseClickHandler(event:MouseEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
mouseClickLogic();
keyPressLogic();
}
function mouseClickLogic():void
{
//do something...
}
function keyPressedHandler(event:KeyboardEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
keyPressLogic();
mouseClickLogic();
}
function keyPressLogic():void
{
//to something...
}

You can use like that:
MouseEvent in flash events:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK,clickStage);
stage.addEventListener(MouseEvent.MOUSE_UP,upStage);
stage.addEventListener(Event.MOUSE_LEAVE,leaveStage);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownStage);
function clickStage(e:MouseEvent):void
{
trace("click Stage");
}
function upStage(e:MouseEvent):void
{
trace("up Stage");
}
function leaveStage(e:Event):void
{
trace("leave Stage");
}
function mouseDownStage(e:MouseEvent):void
{
trace("mouse Down Stage");
}
keyboardEvent function:
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (character code: " + event.charCode + ")");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);

I thank all those who tried to help me
this is my program without any error the error which I made before is in this code instead of Event
I typed MousEvent
function startFun(evt:Event):void
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
var elapsedTime:Number;
var NumOfProplem:Number;
var PropSolved:Number;
var completeSet:Boolean;
answerbox.restrict = "0-9";
ProplemBox.restrict = "0-9";
mult2.restrict = "?";
mult1.restrict = "?";
var keyMode:Number = 0;
stage.focus = ProplemBox;
bt1.visible = false;
bt2.visible = false;
//////////////////////////////
btnstart.addEventListener(MouseEvent.CLICK, startFun);
function startFun(evt:Event):void {
if (ProplemBox.text == "") {
stage.focus = ProplemBox;
return;
}
bt1.visible = true;
bt2.visible = true;
NumOfProplem = Number(ProplemBox.text);
PropSolved = 0;
completeSet = false;
elapsedTime = getTimer();
keyMode = 1;
anotherPro(evt);
}
///////////////////////////////
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
/////////////////
bt1.addEventListener(MouseEvent.CLICK,checkfun);
function checkfun(evt:Event):void
{
var x:Number = parseInt(mult1.text);
var y:Number = parseInt(mult2.text);
var z:Number = parseInt(answerbox.text);
if ((x*y )== z){
messagebox.text = "Right";
PropSolved++;
if (PropSolved >= NumOfProplem ){
keyMode = 3;
endGameReport();
}
else{
keyMode = 2;
}
}
else
{
messagebox.text = "Wrong";
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
}
function endGameReport():void{
elapsedTime = (getTimer() - elapsedTime);
stage.focus = ProplemBox;
ProplemBox.setSelection(0,2);
bt1.visible = false;
bt2.visible = false;
messagebox.text = "You completed" + NumOfProplem + "Proplems in"
+ Math.floor(elapsedTime/1000) + "Second";
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
startFun(evt);
}
else if (keyMode == 1)
{
checkfun(evt);
}
else if (keyMode == 2)
{
keyMode = 1;
anotherPro(evt);
}
}
}

Related

Actionscript 3 - ReferenceError: Error #1065: Variable addFrameScript is not defined

I am getting this error :
ReferenceError: Error #1065: Variable addFrameScript is not defined.
at survival()
I'm having the problem when I run this code :
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.*;
import flash.media.SoundMixer;
import flash.media.SoundTransform;
public class survival extends Sprite {
public var ground:ground_mc = new ground_mc();
public var environment:environment_mc = new environment_mc();
public var player:player_mc = new player_mc();
public var monster:monster_mc = new monster_mc();
public var light:Sprite=new Sprite ;
public var battery:battery_mc = new battery_mc();
public var key_pressed:int=0;
public var radius:int=8;
public var player_speed:int=2;
public var monster_speed:int=1;
public var torch_power:int=150;
public var torch_step:int = 100;
public var torch_angle:int=60;
public var torch_angle_step:int=35;
public var up,down,left,right:Boolean=false;
public var flicker=0;
public var count:int;
public var sec:int;
public var torchBattery:int = 100;
var topLeft:Boolean = true;
var topRight:Boolean = false;
var bottomLeft:Boolean = false;
var bottomRight:Boolean = false;
public function survival():void {
addChild(ground);
addChild(environment);
addChild(light);
addChild(player);
addChild (battery);
addChild(monster);
player.x=250;
player.y=200;
battery.x=321;
battery.y=29;
environment.y = 0;
environment.x = 0;
ground.mask=light;
addEventListener(Event.ENTER_FRAME,on_enter_frame);
addEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.addEventListener(KeyboardEvent.KEY_UP, on_key_up);
}
public function on_enter_frame(e:Event):void {
if (up) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (down) {
environment.y-=player_speed;
ground.y-=player_speed;
monster.y-=player_speed;
}
if (left) {
environment.x+=player_speed;
ground.x+=player_speed;
monster.x+=player_speed;
}
if (right) {
environment.x-=player_speed;
ground.x-=player_speed;
monster.x-=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y+radius, true)) {
environment.y+=player_speed;
ground.y+=player_speed;
monster.y+=player_speed;
}
if (environment.collisions.hitTestPoint(player.x, player.y-radius, true)) {
environment.y-= player_speed;
ground.y-= player_speed;
monster.y-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x-radius, player.y, true)) {
environment.x-= player_speed;
ground.x-= player_speed;
monster.x-= player_speed;
}
if (environment.collisions.hitTestPoint(player.x+radius, player.y, true)) {
environment.x+= player_speed;
ground.x+= player_speed;
monster.x+= player_speed;
}
var dist_x:Number=player.x-mouseX;
var dist_y:Number=player.y-mouseY;
var angle:Number=- Math.atan2(dist_x,dist_y);
player.rotation=to_degrees(angle);
light.graphics.clear();
if (Math.random()*100>flicker) {
light.graphics.beginFill(0xffffff, 100);
light.graphics.moveTo(player.x, player.y);
for (var i:int=0; i<=torch_angle; i+=(torch_angle/torch_angle_step)) {
ray_angle = to_radians((to_degrees(angle)-90-(torch_angle/2)+i));
for (var j:int=1; j<=torch_step; j++) {
if (environment.collisions.hitTestPoint(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle), true)) {
break;
}
}
light.graphics.lineTo(player.x+(torch_power/torch_step*j)*Math.cos(ray_angle), player.y+(torch_power/torch_step*j)*Math.sin(ray_angle));
}
light.graphics.lineTo(player.x, player.y);
light.graphics.endFill();
}
if (torchBattery > 0) {
count += 1;
if (count >= 30) {
count = 0;
sec += 1;
}
if (sec >= 2) {
sec = 0;
flicker += 1;
torchBattery -= 1;
changeMovement();
}
}
battery.battery.text = "Torch Battery: " + torchBattery + "%";
var theDistance:Number = distance(monster.x, player.x, monster.y, player.y);
var myVolume:Number = 2-(0.004* theDistance);
var Volume:Number = myVolume;
if (Volume < 0) {
Volume = 0;
}
SoundMixer.soundTransform = new SoundTransform(Volume);
trace(theDistance);
if (distance < 100) {
removeEventListener(Event.ENTER_FRAME,on_enter_frame);
removeEventListener(Event.ENTER_FRAME,on_enter_frame2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, on_key_down);
stage.removeEventListener(KeyboardEvent.KEY_UP, on_key_up);
removeChild(ground);
removeChild(environment);
removeChild(light);
removeChild(player);
removeChild (battery);
removeChild(monster);
gotoAndStop(2);
}
}
function on_enter_frame2 (e:Event) :void {
if (environment.collisions.hitTestPoint(monster.x, monster.y+radius, true)) {
monster.y -= monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x,monster.y-radius, true)) {
monster.y += monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x-radius, monster.y, true)) {
monster.x+=monster_speed;
}
if (environment.collisions.hitTestPoint(monster.x+radius, monster.y, true)) {
monster.x -= monster_speed;
}
if (topLeft) {
monster.x -= monster_speed;
monster.y -= monster_speed;
} else if (topRight) {
monster.x += monster_speed;
monster.y -= monster_speed;
} else if (bottomLeft) {
monster.x -= monster_speed;
monster.y += monster_speed;
} else if (bottomRight) {
monster.x += monster_speed;
monster.y += monster_speed;
}
}
function changeMovement():void {
var die2:Number = Math.floor(Math.random()*4);
if (die2 == 1) {
topLeft = true;
topRight = false;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 2) {
topLeft = false;
topRight = true;
bottomLeft = false;
bottomRight = false;
}
if (die2 == 3) {
topLeft = false;
topRight = false;
bottomLeft = true;
bottomRight = false;
}
if (die2 == 4) {
topLeft = false;
topRight = false;
bottomLeft = false;
bottomRight = true;
}
}
public function on_key_down(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=true;
break;
case 38 :
up=true;
break;
case 39 :
right=true;
break;
case 40 :
down=true;
break;
/*case 49 :
torch_power++;
break;
case 50 :
torch_power--;
break;*/
}
}
public function on_key_up(e:KeyboardEvent):void {
switch (e.keyCode) {
case 37 :
left=false;
break;
case 38 :
up=false;
break;
case 39 :
right=false;
break;
case 40 :
down=false;
break;
}
}
public function to_radians(n:Number):Number {
return (n*0.0174532925);
}
public function to_degrees(n:Number):Number {
return (n*57.2957795);
}
function distance(x1:Number, x2:Number, y1:Number, y2:Number): Number {
var dx:Number = x1-x2;
var dy:Number = y1-y2;
return Math.sqrt(dx * dx + dy * dy);
}
}
}
On my timeline I have a blank keyframe with the sound effect of a music box playing, and a second frame with the animated jumpscare. The game is that you're in a bird's eye view of a person with a torch walking through a maze. The 'monster' moves around the maze and you must stay away from it. As it gets closer, the music box that is playing will get louder. Also, your torch only has a certain amount of battery. As the battery reduces, the torch will flicker more untill it eventually stops working. It worcked fine until I tried to make the jumpscare. This is all the coding in the game.
In the 'Compiler Errors' it also states:
/Users/ethan/Documents/Flash Stuff/Flash Stuff [from macbook]/survival/survival.as, Line 164 Warning: 1060: Migration issue: The method gotoAndStop is no longer supported. For more information, see MovieClip.gotoAndStop()..
Any suggestions or help I'll be very grateful.
Sprite Class doesn't have gotoAndStop method. This method implemented only in MovieClip class. So, you should replace
public class survival extends Sprite {
with
public class survival extends MovieClip {

How to set only one object to spawn with a timer?

I am currently a beginner trying to learn programming with as3 so bear with me. I have this code so far and my game repeatedly spawns the Food2 (golden apple) but it does not stop. Here is my code so far:
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class Main extends MovieClip{
const speed:int = 10;
var score:int;
var vx:int;
var vy:int;
var gFood:Food;
var gFood2:Food2;
var head:SnakePart;
var SnakeDirection:String;
var snake:Array;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var myTimer:Timer = new Timer(10000,1);
public function Main(){
init();
gotoAndStop(1);
}
function init():void {
vx = 1; vy = 0;
score = 0;
snake = new Array();
SnakeDirection = "";
addFood();
myTimer.start();
head = new SnakePart();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
start1.addEventListener(MouseEvent.CLICK, startgame);
help1.addEventListener(MouseEvent.CLICK, helpplayer);
stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
}
private function startgame(event:MouseEvent):void {
gotoAndPlay(3);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
stop();
}
private function helpplayer(event:MouseEvent):void {
gotoAndPlay(2);
stop();
}
function addFood():void {
gFood = new Food();
gFood.x = 50 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
function addFood2():void {
gFood2 = new Food2();
gFood2.x = 70 + Math.random()*(stage.stageWidth-100);
gFood2.y = 70 + Math.random()*(stage.stageHeight-100);
addChild(gFood2);
}
function reset():void {
gotoAndStop(1);
score = 0;
removeChild(gFood);
removeChild(gFood2);
myTimer.stop();
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
SnakeDirection = "left";
}else if (event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "right";
}else if (event.keyCode == Keyboard.UP) {
SnakeDirection = "up";
}else if (event.keyCode == Keyboard.DOWN) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.LEFT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.UP ) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.DOWN){
SnakeDirection = "";
}
}
function onEnterFrame(event:Event):void {
Timerfood();
txtScore.text = "Score:" + String(score);
if(SnakeDirection == "left" && vx != 1) {
vx = -1;
vy = 0;
}
else if(SnakeDirection == "right" && vx != -1) {
vx = 1;
vy = 0;
}
else if(SnakeDirection == "up" && vy != 1) {
vx = 0;
vy = -1;
}
else if(SnakeDirection == "down" && vy != -1) {
vx = 0;
vy = 1;
}
if(head.x - head.width/2 <= 0){
score = 0;
reset();
}
if(head.x + head.width/2 >= stage.stageWidth){
score = 0;
reset();
}
if(head.y - head.height/2 <= 0){
score = 0;
reset();
}
if(head.y + head.height/2 >= stage.stageHeight){
score = 0;
reset();
}
for(var i = snake.length-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
head.x += vx*speed;
head.y += vy*speed;
for(var i = snake.length-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
if(head.hitTestObject(gFood)){
score += 1;
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
score += 2;
removeChild(gFood2);
bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
function Keyboard_a(event:KeyboardEvent):void {
if (event.keyCode == 82) {
resetgame();
}
}
function resetgame():void {
score = 0;
if (contains(head))
removeChild(head);
init();
}
}
function Timerfood():void {
var myTimer:Timer = new Timer(10000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void{
trace("Timer is Triggered");
addFood2();
}
myTimer.start();
}
}
}
It's hard to understand what specific logic you want to implement, but it looks like you need to create an enemy only once. And it looks like the problem is: you call the Timerfood method in the onEnterFrame listeners, which itself is called many times per second according to the framerate of your app (e.g. 30 times per second).
I would suggest you to remove the call of Timerfood from the onEnterFrame method, and put it in the end of the init method.
Well, my English is not very good, but I try tell the possible reason,
the method Timerfood() is called on method onEnterFrame(), that initialize myTimer for each frame, so may be the solution is, remove this line into TimerFood() method:
var myTimer:Timer = new Timer(10000,1);
and call TimerFood() only in startgame() method.
I hope you can understand me.

How do I call methods and properties from parent classes?

I'm new here (and also relatively new with AS3 as well), so bear with me.
I've only discovered OOP 2 weeks ago, and before then, I knew only the most rudimentary knowledge of AS3. So I did make a lot of improvement, but one thing's been bugging me.
I can never seem to call functions and methods from parent classes. Even with setters and getters, the child class always gives me an output error. It looks something like this.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Axiom/clicked()
This is an AS3 project that I'm working on right now that is giving me this problem.
Here's some basic background of the project.
I have the main class, called Main, and some other classes, called Axiom and Textbox. Main creates Axiom into a movieclip (background) that's already present on the stage. Axiom creates Textbox when clicked. Axiom calls a method called mouseClick from Main (plays a sound), and Textbox calls some properties from Axiom (text for the textbox).
I have attempted to use
MovieClip(this.parent).mouseClick();
and declaring a new variable in the child class, like this.
private var main:Main;
...
main.mouseClick();
And this leads me to question - what am I doing wrong, and how should I do it properly?
Here are the classes for reference.
Main.as
package {
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Mouse;
import flash.events.MouseEvent;
public class Main extends MovieClip {
// sound
private var music:Music = new Music();
private var clickSound:Click = new Click();
// instructions
private var instructions:Instructions = new Instructions();
// mouse
private var cursor:Cursor = new Cursor();
// player
private var player:Player = new Player();
private var animationState:String = "standing";
private var directionState:String = "right";
// Axiom
private var axiom:Axiom = new Axiom();
// movement
private var rightPressed:Boolean = false;
private var leftPressed:Boolean = false;
private var upPressed:Boolean = false;
private var downPressed:Boolean = false;
private var xMovement:Number = 0;
private var yMovement:Number = 0;
private var speed:Number = 22;
private var friction:Number = 0.9;
private var rDoubleTapCounter:int = 0;
private var lDoubleTapCounter:int = 0;
private var dDoubleTapCounter:int = 0;
private var uDoubleTapCounter:int = 0;
private var doubleTapCounterMax:int = 5;
private var running:Boolean = false;
public function Main() {
// constructor code
// mouse
stage.addChild(cursor);
cursor.mouseEnabled = false;
Mouse.hide();
// instructions
instructions.x = 640;
instructions.y = 120;
stage.addChild(instructions);
// add player
player.x = 642;
player.y = 448.95;
player.gotoAndStop(directionState);
player.right.gotoAndStop(animationState);
addChild(player);
// add Axiom
axiom.x = 300;
axiom.y = -150;
back.addChild(axiom);
// keyboard events
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
// music
music.play(0, int.MAX_VALUE);
// loop
stage.addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void {
// set mouse
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
// set Movement to speed
if (rightPressed) {
if (upPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * -2;
} else {
xMovement = speed;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * 2;
} else {
xMovement = speed;
yMovement = speed;
}
} else if (running || rDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * 2;
} else {
xMovement = speed;
}
} else if (leftPressed) {
if (upPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * -2;
} else {
xMovement = speed * -1;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * 2;
} else {
xMovement = speed * -1;
yMovement = speed;
}
} else if (running || lDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * -2;
} else {
xMovement = speed * -1;
}
} else if (downPressed) {
if (dDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
} else if (upPressed) {
if (uDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
}
// double tap counter
if (rightPressed == false) {
rDoubleTapCounter++;
}
if (leftPressed == false) {
lDoubleTapCounter++;
}
if (downPressed == false) {
dDoubleTapCounter++;
}
if (upPressed == false) {
uDoubleTapCounter++;
}
// change labels
if (player.currentLabel != animationState) {
player.right.gotoAndStop(animationState);
}
// friction
xMovement *= friction;
yMovement *= friction;
// animationState and stop
if (Math.abs(xMovement) > 1) {
if (Math.abs(xMovement) > 22) {
animationState = "running";
running = true;
} else {
animationState = "trotting";
running = false;
}
} else {
animationState = "standing";
xMovement = 0;
}
// right or left facing
if (xMovement > 0) {
player.scaleX = 1;
} else if (xMovement < 0) {
player.scaleX = -1;
}
//movement
if (back.x >= back.width / 2 - 50) {
if (player.x >= 642 && xMovement > 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x <= player.width / 2 && xMovement < 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else if (back.x <= 1280 - back.width / 2 + 50) {
if (player.x <= 642 - 30 && xMovement < 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x >= 1280 + 30 - player.width / 2 && xMovement > 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else {
back.x -= xMovement;
}
}
private function keyPressed(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = true;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = true;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = true;
} else if (e.keyCode == Keyboard.UP) {
upPressed = true;
}
}
private function keyReleased(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = false;
rDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = false;
lDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = false;
dDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.UP) {
upPressed = false;
uDoubleTapCounter = 0;
}
}
public function mouseClick():void {
clickSound.play();
}
}
}
Axiom.as
package {
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main;
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
main.mouseClick();
stage.addChild(speechBox);
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
Textbox.as
package {
import flash.events.MouseEvent;
import flash.display.MovieClip;
import com.greensock.TweenLite;
public class Textbox extends MovieClip{
private var axiom:Axiom;
private var main:Main;
public function Textbox() {
// constructor code
this.x = 40;
this.y = 360;
this.textBox.text = axiom.words;
TweenLite.from(this, 0.3, {x: "10", alpha: 0});
this.addEventListener(MouseEvent.CLICK, nextPage);
}
private function nextPage(e:MouseEvent):void{
main.mouseClick();
TweenLite.to(this, 0.3, {x: "-10", alpha: 0});
MovieClip(this.parent).removeThis();
}
}
}
Instead of trying to call functions of the parent (rarely a good idea), use Events instead.
In your Axiom Class:
package {
...import statements
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main; //this shouldn't be here, ideally, Axiom knows NOTHING about the main class.
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
//main.mouseClick(); // unneccesary
dispatchEvent(e); //the event you caught by performing a click will be dispatched again, so that the parent can react to it
stage.addChild(speechBox); //Axiom might not have access to the stage, addChild would suffice
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
and in your Main Class
axiom.addEventListener(MouseEvent.CLICK, onAximClicked);
private function onAxiomClicked(e:MouseEvent):void{
//now you can use the parents (in this case an Object of the Main class) functions
mouseClick();
}

Flash - Pause Game ActionScript 3

I'm only a beginner and this code is somewhere in the internet that I just want to learn
This is a snake game, I want to pause a game using spacebar keyboard
I don't know how to pause a game someone please help
import flash.ui.*;
public class Snake extends MovieClip
{
private var _Paused:Boolean = false
private var score, life, framesElapsed:Number;
private var p1speedX, p1speedY:Number;
private var spacePressed, readyToMove, gotoWin, gotoLose:Boolean;
private var left,right,up,down:Boolean;
private var snakes:Array;
private var mcFood:Food;
public function Snake()
{
}
//All Start Functions
public function startMenu()
{
stop();
btnStartGame.addEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.addEventListener(MouseEvent.CLICK, gotoHowToPlay);
}
public function startHowToPlay()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startWin()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startLose()
{
btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
}
public function startGame()
{
score = 0;
life = 3;
framesElapsed = 0;
p1speedX = 1; //snakek starts moving right
p1speedY = 0;
up = false;
down = false;
left = false;
right = false;
spacePressed = false;
readyToMove = false;
gotoWin = false;
gotoLose = false;
snakes = new Array();
//Create 1st body part of snake and push it into the array
var snakeHead = new SnakePart();
snakeHead.x = 400;
snakeHead.y = 300;
snakes.push(snakeHead);
addChild(snakeHead);
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.focus = this;
}
//All Goto Functions
private function gotoStartGame(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("game");
}
private function gotoHowToPlay(evt:MouseEvent)
{
btnStartGame.removeEventListener(MouseEvent.CLICK, gotoStartGame);
btnHowToPlay.removeEventListener(MouseEvent.CLICK, gotoHowToPlay);
gotoAndStop("howtoplay");
}
private function gotoMenu(evt:MouseEvent)
{
btnBack.removeEventListener(MouseEvent.CLICK, gotoMenu);
gotoAndStop("menu");
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
//1st Player Left Key
left = true;
}
else if (evt.keyCode == Keyboard.D)
{
//1st Player Right Key
right = true;
}
if (evt.keyCode == Keyboard.W)
{
//1st Player Up Key
up = true;
}
else if (evt.keyCode == Keyboard.S)
{
//1st Player Down Key
down = true;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = true;
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.A)
{
left = false;
}
else if (evt.keyCode == Keyboard.D)
{
right = false;
}
else if (evt.keyCode == Keyboard.W)
{
up = false;
}
else if (evt.keyCode == Keyboard.S)
{
down = false;
}
if (evt.keyCode == Keyboard.SPACE)
{
spacePressed = false;
}
}
public function update(evt:Event)
{
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
private function handleUserInput()
{
//Handle player 1 position
//if player wants to move left but snake is not
//already moving right
if (left && (p1speedX != 1))
{
p1speedX = -1;
p1speedY = 0;
}
//if player wants to move right but snake is not
//already moving left
else if (right && (p1speedX != -1 ))
{
p1speedX = 1;
p1speedY = 0;
}
//if player wants to move up but snake is not
//already moving down
else if (up && (p1speedY != 1))
{
p1speedY = -1;
p1speedX = 0;
}
else if (down && (p1speedY != -1))
{
p1speedY = 1;
p1speedX = 0;
}
if (spacePressed)
readyToMove = true;
}
private function handleGameLogic()
{
if (!readyToMove)
return;
framesElapsed++;
//Update the new position of the snake's head
if (framesElapsed % 2 == 0)
{
//Update motion of the snake's body
for (var i = snakes.length - 1; i >= 1; i--)
{
snakes[i].x = snakes[i-1].x;
snakes[i].y = snakes[i-1].y;
}
if (p1speedX > 0)
{
snakes[0].x += 20;
}
else if (p1speedX < 0)
{
snakes[0].x -= 20;
}
else if (p1speedY > 0)
{
snakes[0].y += 20;
}
else if (p1speedY < 0)
{
snakes[0].y -= 20;
}
//Check for collisions between the snake and its own body
for (var i = snakes.length - 1; i >= 1; i--)
{
if ((snakes[0].x == snakes[i].x) &&
(snakes[0].y == snakes[i].y))
{
collided();
break;
}
}
}
//Check for collisions between the snake and the walls
if (snakes[0].y < 0)
{
collided();
}
else if (snakes[0].x > 800)
{
collided();
}
else if (snakes[0].x < 0)
{
collided();
}
else if (snakes[0].y > 600)
{
collided();
}
//Add new food items
if (mcFood == null)
{
//Create a new food item
mcFood = new Food();
mcFood.x = Math.random() * 700 + 50;
mcFood.y = Math.random() * 500 + 50;
addChild(mcFood);
}
//Check for collisions between food item and Snake
if (mcFood != null)
{
if (snakes[0].hitTestObject(mcFood))
{
//Add score
score += 100;
if (score >= 5000)
gotoWin = true;
removeChild(mcFood);
mcFood = null;
//Add a body
var newPart = new SnakePart();
newPart.x = snakes[snakes.length-1].x;
newPart.y = snakes[snakes.length-1].y;
snakes.push(newPart);
addChild(newPart);
}
}
}
private function handleDraw()
{
//Handle display
if (!readyToMove)
txtHitSpaceBar.visible = true;
else
txtHitSpaceBar.visible = false;
txtScoreP1.text = String(score);
txtLife.text = String(life);
}
private function triggerGoToWin()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("win");
}
private function triggerGoToLose()
{
clearGame();
removeEventListener(Event.ENTER_FRAME, update);
gotoAndStop("lose");
}
//Misc Functions
private function resetGame()
{
//remove all food
removeChild(mcFood);
mcFood = null;
//remove all of snake body except first
for (var i = snakes.length - 1; i >= 1; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
//Center the snake's head
snakes[0].x = 400;
snakes[0].y = 300;
readyToMove = false;
}
private function clearGame()
{
//remove all food
if (mcFood != null)
{
removeChild(mcFood);
mcFood = null;
}
//remove all of snake body
for (var i = snakes.length - 1; i >= 0; i--)
{
removeChild(snakes[i]);
snakes.splice(i,1);
}
}
private function collided()
{
life -= 1;
if (life > 0)
resetGame();
else
gotoLose = true;
}
}
}//end class
//end package
There are a few possibilities how to pause a game.
You already have a boolean variable called _Paused, this will help us to determine when to pause the execution of the game.
Change the contents of keyDownHandler(evt) to the following:
private function keyDownHandler(evt:KeyboardEvent)
{
...
//leave the if conditionals for movement as they are
if (evt.keyCode == Keyboard.SPACE)
{
if(_Pause == true){
_Pause = false;
}else{
_Pause = true;
}
}
}
The above code will toggle between a Paused state and the Game state. When the game first starts, the _Paused variable is false. Once you press Space on your keyboard, the if condition will check what state you need to be in. So at the very first time, _Paused will be set to true. if you press space again, it will set it to false again. Simple, right?
Now, you have an EventListener for ENTER_FRAME called update that executes for every frame. This function is responsible that things, well, work. You can see that it calls different functions that draw stuff on the screen or handle game logic. So, what would happen if you don't call this function? The game would stop. So we need a way to not call those functions when you are in your pause state. Again, this is very simple.
Change the contents of update(evt) to the following:
public function update(evt:Event)
{
if(_Paused == false){
handleUserInput();
handleGameLogic();
handleDraw();
if (gotoWin)
triggerGoToWin();
else if (gotoLose)
triggerGoToLose();
}
}
Now the functions will only be called when your _Paused variable is set to false.
I hope this helped you with your studying, although this is very basic stuff. Maybe you should try smaller steps first? Programming games can be pretty complex for beginner who have no experience with coding whatsoever.

TypeError: Error #1009: Cannot access a property or method of a null reference

I am creating a platformer game. However, I have encountered an error after creating a collision boundary on platform to make the player jump on the platform without dropping.
I have create a rectangle box and I export it as platForm
Here's the output of the error:
The error keep repeating itself over and over again....
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Boy/BoyMove()
Main class:
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class:
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 15;
//whether or not the main guy is jumping
//var mainJumping:Boolean = false;
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var gravity:Number = 10;
var theGround:ground = new ground();
//var theCharacter:MovieClip;
public var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, BoyMove);
}
public function BoyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (MovieClip(this).y > 500)
{
mainJumping = false;
MovieClip(this).y = 500;
}
this.y = currentY;
}
}
}
Platformer class: This is the class I want to set the boundary for the rectangle (platForm)
package
{
import flash.events.*;
import flash.display.MovieClip;
public class platForm extends MovieClip
{
var level:Array = new Array();
var classBoys:Boy = new Boy();
var speedx:int = MovieClip(classBoys).currentX;
public function platForm()
{
for (var i = 0; i < numChildren; i++)
{
if (getChildAt(i) is platForm)
{
level.push(getChildAt(i).getRect(this));
}
}
for (i = 0; i < level.length; i++)
{
if (MovieClip(classBoys).getRect(this).intersects(level[i]))
{
if (speedx > 0)
{
MovieClip(classBoys).x = level[i].left - MovieClip(classBoys).width/2;
}
if (speedx < 0)
{
MovieClip(classBoys).x = level[i].right - MovieClip(classBoys).width/2;
}
}
}
}
}
}
It's a little difficult to see exactly what is happening without being able to run your code, but the error is saying that something within your BoyMove() method is trying to reference a property (or method) of something that is null. Having looked at the BoyMove() method, I can see that there isn't a lot there that could cause this problem. The other two candidates would be
MovieClip(parent)
or
MovieClip(this)
You are attempting to access properties of both of those MovieClips. One of them must not be initialized as you expect. I suggest you do some basic debugging on that method by commenting out the lines with MovieClip(parent) and see if you still get the error. Then try the same with the line with MovieClip(this). That should be able enough to isolate the issue.