Why does my shark not get damaged when colliding with other sharks? - actionscript-3

I also get errors on my output such as:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_AnimateHorizontally_2()
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
AttackonSharkwithMovement_fla::MainTimeline/fl_EnterFrameHandler_2()[
Scene 1 - Main Menu
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand
import flash.events.MouseEvent
stop();
//Button Scripts
Play_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
function fl_ClickToGoToScene(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_10);
function fl_ClickToGoToAndStopAtFrame_10(event:MouseEvent):void
{
gotoAndStop(6);
}
function quit (event:MouseEvent):void
{
fscommand ("quit");
}
Quit_Button.addEventListener(MouseEvent.MOUSE_DOWN,quit);
Scene 2 - Game
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
import flash.system.fscommand;
import flash.events.TimerEvent;
import flash.utils.Timer;
stop();
//Variables
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var sharkSpeed:Number = 10;
var score1:Number = 0;
var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
//Health Script
function updateHealthBar():void
{
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
}
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_2);
function fl_ClickToGoToScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
Instructions_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextScene_2);
function fl_ClickToGoToNextScene_2(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(6, "Main Menu");
}
//Keyboard Movement
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
function keyDownHandler(KeyEvent:KeyboardEvent):void
{
if (KeyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
else if (KeyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
}
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if (keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
}
else if (keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
}
else if (keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
}
else if (keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
}
}
function gameLoop(loopEvent:Event):void
{
if (rightPressed)
{
shark.x += sharkSpeed;
}
else if (leftPressed)
{
shark.x -= sharkSpeed;
}
else if (downPressed)
{
shark.y += sharkSpeed;
}
else if (upPressed)
{
shark.y -= sharkSpeed;
}
}
//AI Movement
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
function fl_AnimateHorizontally(event:Event)
{
enemy1.x += 2;
enemy2.x += 2;
enemy3.x += 2;
enemy4.x += 2;
enemy5.x += 2;
enemy6.x += 2;
megaladon.x += 2;
}
addEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally_2);
function fl_AnimateHorizontally_2(event:Event)
{
fishes.x += 1.5;
}
//Colission
function hitsTheObject(e:Event)
{
if (shark.hitTestObject(enemy1))
{
trace("player collided with enemy");
currentHP -= 50;
if (currentHP <= 0)
{
currentHP = 0;
trace("You died!");
MovieClip(this.root).gotoAndPlay(1, "Game Over");
}
updateHealthBar();
}
}
//Score Script
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler_2);
function fl_EnterFrameHandler_2(event:Event):void
{
gameScore.text = String(score1);
score1 += 1;
trace("gameScore.text is : " + gameScore.text);
trace("score1 is : " + score1);
}
//Timer Script
var myTimer:Timer = new Timer(1000,50);
myTimer.addEventListener(TimerEvent.TIMER, onTimer);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
myTimer.start();
function onTimer(e: TimerEvent):void
{
myText_txt.text = String(myTimer.repeatCount - myTimer.currentCount);
}
function onComplete(e: TimerEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "You Survived");
}
Scene 3 - You Survived
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_4);
function fl_ClickToGoToScene_4(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_12);
function fl_ClickToGoToScene_12(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}Scene 4 - Game Over
stop();
//Button Scripts
MainMenu_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_9);
function fl_ClickToGoToScene_9(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Main Menu");
}
PlayAgain_Button.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_11);
function fl_ClickToGoToScene_11(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "Game");
}

As identified in the comments, you need to remove the eventListener which you can achieve with:
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);.
I would suggest implementing the following line whenever you bind to a frame event such as Event.ENTER_FRAME
this.addEventListener(Event.REMOVED_FROM_STAGE, function(){
try{
removeEventListener(Event.ENTER_FRAME, fl_AnimateHorizontally);
}catch(error){
//error handling optional in this case.
}
});
This will get called ONCE only right before the object is destroyed/removed from the stage i.e. when you call MovieClip(this.root).gotoAndPlay(1, "Game");
Note: You can just put all of your 'global' events into the try area - you don't need this call every time you add an event.
Additionally, you don't need this whatsoever for movieclips as all of your events will get cleaned up automatically once they are removed from the stage via the garbage collector.

Related

How to get my game to restart after 2 minutes?

so I'm new to AS3, and have struggled to get to this point, so sorry for any errors or nooby mistakes.
All I want now, is for my game to restart after 2 minutes has passed. Does anyone know how I can do this? I'm at a complete loss.
Here is my code:
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import Ship;
import Coin;
import CoinB;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.utils.getTimer;
public class Main extends Sprite
{
// constructor code
private var Player1:Ship;
private var Coin1:Coin;
private var Coin2:Coin;
private var Coin3:CoinB;
private var Coin4:CoinB;
private var score:int = 0;
private var container;
/*private var timer:Timer;*/
public function Main():void
{
//Sets the position of player
//adds player to stage
this.Player1 = new Ship(259,365);
addChild(this.Player1);
Cont.visible = false;
{
addChild(interval_timer);
/*addChild(frame_timer);*/
/*frame_timer.y = 50;*/
var time_count:Timer = new Timer(1000);
time_count.addEventListener(TimerEvent.TIMER, show_time);
stage.addEventListener(Event.ENTER_FRAME,on_enter_frame);
time_count.start();
}
//adds event listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, hit);
stage.addEventListener(Event.ENTER_FRAME, death);
stage.addEventListener(KeyboardEvent.KEY_DOWN, retry);
//add a Coin here
Coin1 = new Coin(stage.stageWidth / 2,stage.stageHeight / 2,75,10);
stage.addChild(Coin1);
Coin2 = new Coin(stage.stageWidth / 2,stage.stageHeight / 2,125,-5);
stage.addChild(Coin2);
Coin3 = new CoinB(stage.stageWidth / 2,stage.stageHeight / 2,25,15);
stage.addChild(Coin3);
this.addEventListener(Event.ENTER_FRAME, fire);
}
public function show_time(event:TimerEvent)
{
interval_timer.text = event.target.currentCount;
}
public function on_enter_frame(event:Event)
{
var elapsed = getTimer();
public function fire(e:Event)
{
if (Player1.hitTestObject(Coin1))
{
score += 50;
Score.text = score.toString();
}
if (Player1.hitTestObject(Coin2))
{
score += 10;
Score.text = score.toString();
}
}
public function death(e:Event)
{
if (Player1.hitTestObject(Coin3))
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, hit);
score = 0;
Score.text = score.toString();
/* gameOver.visible = true;*/
Cont.visible = true;
this.removeChild(this.Player1);
this.Player1 = new Ship(259,365);
Coin1.visible = false;
Coin2.visible = false;
Player1.visible = false;
Coin3.visible = false;
removeChild(interval_timer);
}
}
public function hit(evt:KeyboardEvent):void
{
//this will move the player right if the "Right" arrow key is pressed.
if (evt.keyCode == Keyboard.RIGHT)
{
this.Player1.right();
this.Player1.rotation = 90;
}
//this will move the player left if the "Left" arrow key is pressed.
else if (evt.keyCode == Keyboard.LEFT)
{
this.Player1.left();
this.Player1.rotation = 270;
}
if (evt.keyCode == Keyboard.DOWN)
{
this.Player1.down();
this.Player1.rotation = 180;
}
//this will move the player up if the "Up" arrow key is pressed.
else if (evt.keyCode == Keyboard.UP)
{
this.Player1.up();
this.Player1.rotation = 0;
}
}
public function retry(evt:KeyboardEvent):void
{
//restarts game.
//adds event listener so that the player can move again
if (evt.keyCode == Keyboard.R)
Cont.visible = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, hit);
Coin1.visible = true;
Coin2.visible = true;
Player1.visible = true;
Coin3.visible = true
addChild(this.Player1);
addChild(interval_timer);
}
}
}
Any help is greatly appreciated. Thanks.
Generally speaking, you would use a Timer to trigger a function when 2 minutes is up.
Something like this:
var gameTimer:Timer = new Timer(120 * 1000); // 120 seconds * 1000 milliseconds
gameTimer.addEventListener(TimerEvent.TIMER, onGameTimerTick);
gameTimer.start();
function onGameTimerTick(e:TimerEvent):void {
//stop the timer
gameTimer.removeEventListener(TimerEvent.TIMER, onGameTimerTick);
gameTimer.stop();
restartMyGame();
}

flash transition tween with keyboard

thanks for any help you can provide
I want a movieclip to move left or right with easing so I am using flash's tween .The code is below. Problem I am face is that when I am clicking left key it moves on once rather than to keep moving while i keep pressing the key and same with right key. Some help please? Thanks.
//variable declarations
var Currpos:Number = boat_mc.x ;
var xleft:Number = boat_mc.x - 40;
var xright:Number = boat_mc.x + 40;
// move boat
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyboardClick);
function onKeyboardClick (e:KeyboardEvent):void{
if (e.keyCode == Keyboard.LEFT){
var tweenleft:Tween = new Tween(boat_mc, "x", Regular.easeOut, Currpos, xleft, 2, true);
}
if (e.keyCode == Keyboard.RIGHT){
var tweenright:Tween = new Tween(boat_mc, "x", Regular.easeOut, Currpos, xright, 2, true);
}
}
based on your answer serhatsezer I was able to fix the problem, thanks
The main problem I was doing was i was declaring the variables outside the function so it was not getting updated
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.text.TextFieldAutoSize;
import flash.text.TextField;
import flash.ui.Mouse;
import flash.display.DisplayObjectContainer;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import mochi.as3.*;
//variable declaration
var isRightPressed:Boolean = false;
var isLeftPressed:Boolean = false;
var tweenleft:Tween;
var tweenright:Tween;
// move boat
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyboardClick);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyboardUp);
function onKeyboardClick(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
isLeftPressed = true;
}
if (e.keyCode == Keyboard.RIGHT)
{
isRightPressed = true;
}
}
function onKeyboardUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
isLeftPressed = false;
}
if (e.keyCode == Keyboard.RIGHT)
{
isRightPressed = false;
}
}
stage.addEventListener(Event.ENTER_FRAME,loop);
function loop(event:Event):void
{
//variable declrations
var Currpos:Number = boat_mc.x;
var xleft:Number = boat_mc.x - 40;
var xright:Number = boat_mc.x + 40;
if (isRightPressed)
{
tweenright = new Tween(boat_mc, "x", Regular.easeOut, Currpos, xright, 2, true);
trace(boat_mc.x);
}
if (isLeftPressed)
{
tweenleft = new Tween(boat_mc, "x", Regular.easeOut, Currpos, xleft, 2, true);
trace(boat_mc.x);
}
}
I think you're trying to wrong way to do this. You have to control your pressed key at ENTER_FRAME listener. After that move them! But keep in mind you have to update variables in your function.
import fl.transitions.Tween;
import fl.transitions.easing.Regular;
import flash.events.Event;
var Currpos:Number = boat_mc.x;
var xleft:Number = boat_mc.x - 40;
var xright:Number = boat_mc.x + 40;
var isRightPressed:Boolean = false;
var isLeftPressed:Boolean = false;
// move boat
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyboardClick);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyboardUp);
function onKeyboardClick(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
isLeftPressed = true;
}
if (e.keyCode == Keyboard.RIGHT)
{
isRightPressed = true;
}
}
function onKeyboardUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
isLeftPressed = false;
}
if (e.keyCode == Keyboard.RIGHT)
{
isRightPressed = false;
}
}
stage.addEventListener(Event.ENTER_FRAME,loop);
var xSpeed:Number = 0.8;
function loop(event:Event):void
{
if (isRightPressed)
{
boat_mc.x += xSpeed;
}
if (isLeftPressed)
{
boat_mc.x -= xSpeed;
}
}
I hope this help. Cheers!

Strange issue with preloader

I have some problem with my preloader.
Preloader Code:
import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;
var game:MovieClip
var added:Boolean;
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest("source.swf");
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
mLoader.load(mRequest);
function onCompleteHandler(e:Event):void {
game = e.currentTarget.content
game.alpha = 0;
}
function onProgressHandler(e:ProgressEvent):void {
loader.loadBar.setProgress(e.bytesLoaded, e.bytesTotal);
}
addEventListener(Event.ENTER_FRAME, function(e:Event):void {
if(game != null){
if(!added) {
addChild(game);
added = true;
}
if(game.alpha < 1) game.alpha += 0.1;
When I load my game console returns TypeError: Error #1009: Cannot access a property or method of a null object reference.
I turn on permit debugging in game and again load. Now console returns TypeError: Error #1009: Cannot access a property or method of a null object reference.
at main()[C: \Users\Lukasz\Desktop\Flash\rs\main.as:141];
So I checked 141 line and since 141 to 155 I have keyboard events.
stage.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void {
if(e.keyCode == 32 && moveAvailable) {
startEvent();
}else if(e.keyCode == 32) {
moveAvailable = true;
}
moveSpeed = 70;
});
stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void {
if(e.keyCode == 32) {
moveSpeed = 140
if(!startBtn.enb) moveAvailable = false;
}
});
When I get comment /**/ between this code game load correctly.
By the way I try this.parent and parent. instead of stage. but nothing changed :(
Someone have idea on this problem ?
You need check stage before use it
if (stage) {
addStageEvent();
} else {
this.addEventListener(Event.ADDED_TO_STAGE, addStageEvent);
}
function addStageEvent(e:Event = null):void {
//put the 141-155 line code here
}

Function is undefined for no apparent reason

I have two event listeners calling two functions, the first checkKeyDown and then the second checkKeyUp.
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);
}
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(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
charSpeed = 0;
}
if (e.keyCode == Keyboard.RIGHT){
charSpeed = 0;
}
}
When I first typed the code, I did the checkKeyDown function first, and when I ran it, it worked fine (without the checkKeyUp event listener of course). After this, i added the event listener and checkKeyUp function to the code, but I got an error saying "1120: Access of undefined property checkKeyUp." I have no idea why this has come up, as the checkKeyDown function works fine. If I could get some help on why I am getting this error, that would be great.
You forget a brace (char '}') at the end of checkKeyDown function.

AS3 error 1061 trying to get collision

" Player.as, Line 59 1061: Call to a possibly undefined method hitTestObject through a reference with static type Class."
I am new to flash and am trying to make a game, specifically I am trying to make it so the player class in a game can collide with things, I am using a square at the bottom of his feet (not yet referenced in the code) and a MovieClip called collisionTest
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import KeyObject;
public class Player extends MovieClip
{
public var stageRef:Stage;
public var key:KeyObject;
//add these four variables:
public var leftPressed:Boolean = false; //keeps track of whether the left arrow key is pressed
public var rightPressed:Boolean = false; //same, but for right key pressed
public var upPressed:Boolean = false; //...up key pressed
public var downPressed:Boolean = false; //...down key pressed
private var gravity:Number = 2;
private var runSpeed:Number = 5;
private var touchingGround:Boolean = false;
public var vPressed:Boolean = false;
public function Player(stageRef:Stage, X:int, Y:int):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
key = new KeyObject(stageRef);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
public function loop(e:Event):void
{
checkKeypresses(); //call "checkKeypresses()" every frame
checkCollisions();
if(leftPressed)
{
x -= runSpeed;
}else if(rightPressed)
{
x += runSpeed;
}
if(upPressed)
{
y -= runSpeed;
}else if(downPressed)
{
y += runSpeed;
}
}
public function checkCollisions():void
{
**(this is line 59)** if(Player.hitTestObject(Player.collisionTest)){
touchingGround = true;
trace("gounded");
}
}
public function checkKeypresses():void
{
// I used http://www.dakmm.com/?p=272 as a reference to get the keyCode numbers for each key
if(key.isDown(37) || key.isDown(65)){ // if left arrow or A is pressed
leftPressed = true;
//trace("left pressed");
} else {
leftPressed = false;
}
if(key.isDown(38) || key.isDown(87)){ // if up arrow or W is pressed
upPressed = true;
//trace("up pressed");
} else {
upPressed = false;
}
if(key.isDown(39) || key.isDown(68)){ //if right arrow or D is pressed
rightPressed = true;
//trace("right pressed");
} else {
rightPressed = false;
}
if(key.isDown(40) || key.isDown(83)){ //if down arrow or S is pressed
downPressed = true;
//trace("down pressed");
} else {
downPressed = false;
}
}
}
}
Function hitTestObject isn't a static function, so you should call it from an object instance, same to the collisionTest.
So it should be
this.hitTestObject(collisionTest);//set collisionTest in the Player class