flash transition tween with keyboard - actionscript-3

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!

Related

AS3 ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller

I am making a minions game. My minion's instance name is sideMinion. The bananas are falling and everything works fine, but my removeChild() doesn't work properly. The error I'm getting is
Error #2025: The supplied DisplayObject must be a child of the caller.
The removeChild() or the hitTestObject doesn't work properly.
This is what I have in my banana as. class:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.Event;
public class banana extends MovieClip {
var velX: Number = 0;
var velY: Number = 0;
var falling: Boolean = false;
var gravity: Number = 0;
public function banana() {
var timing: Timer = new Timer(25, 0);
timing.addEventListener(TimerEvent.TIMER, moveMe);
timing.start();
}
private function moveMe(event: TimerEvent)
{
x += velX;
y += velY;
if (falling) velY += gravity;
/* trace("[BANANA] position:", x, y, "speed:", velX, velY);*/
}
public function setSpeed(dx,dy) {
velX = dx;
velY = dy;
}
public function setSpot(atX,atY){
this.x=atX;
this.y=atY;
}
public function makeItFall (){
falling=true;
}
}
}
And in my main program:
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
var leftKey:Boolean;
var rightKey:Boolean;
var upKey:Boolean;
var downKey:Boolean;
var jump:Boolean = false;
var xvelocity:int = 9;
var yvelocity:int = 3;
var gravity:Number = 7;
stage.addEventListener(Event.ENTER_FRAME, changeVelocity);
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeyDown);
function changeVelocity(evt:Event){
moveMinion();
yvelocity += gravity;
}
function moveMinion(){
if (leftKey == true){
sideMinion.x -= xvelocity;
sideMinion.left();
}
if (rightKey == true){
sideMinion.x += xvelocity;
sideMinion.right();
}
}
function checkKeyDown(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
leftKey = true;
}
else if (e.keyCode == Keyboard.RIGHT){
rightKey = true;
}
}
function checkKeyUp(e:KeyboardEvent){
if (e.keyCode == Keyboard.LEFT){
leftKey = false;
}
else if (e.keyCode == Keyboard.RIGHT){
rightKey = false;
}
}
btnStart.addEventListener(MouseEvent.CLICK, makeItFall);
function makeItFall(e:MouseEvent){
var numBananas = 6;
var theBananas: Array = new Array();
theBananas = [];
for (var i = 0; i < numBananas; i++) {
var aBanana: banana = new banana();
theBananas.push(aBanana);
btnStart.visible=false;
aBanana.y=30;
theBananas[i].setSpot(Math.random()*450+50,Math.random()*200+20);
theBananas[i].setSpeed((Math.random()), 1);
stage.addChild(aBanana);
}
var health: uint= 1;
addEventListener(Event.ENTER_FRAME, pickUpBananas);
function pickUpBananas(event:Event){
for( var i= 0; i<theBananas.length; ++i){
if (sideMinion.hitTestObject(theBananas[i])){
removeChild(theBananas[i]);
health=health+1;
trace(health);
}
}
}
}
stop();
Edit : format code
As you are adding child to stage, you'll have to remove it also from stage:
stage.removeChild(theBananas[i]);
For future, in some situations you can also use parent property if you don't know the actual parent:
theBananas[i].parent.removeChild(theBananas[i]);
In your game, I assume you want also to remove the bananas from theBananas-array when you remove bananas from stage, so that your array wont end up having already deleted bananas. So, here's couple modifications:
for(var i:int = theBananas.length-1; i>-1; i--){ //inverted loop
if (sideMinion.hitTestObject(theBananas[i])){
stage.removeChild(theBananas[i]);
theBananas.splice(i,1); //removing it from the array
health=health+1;
trace(health);
}
}
Inverted loop obviously loops from last element all the way to the first one, becouse if you'd remove the first element from the array, then second element would 'jump' into its place and loop would skip it.
I hope we all will soon get to see your game! :)

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

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.

5006: An ActionScript file can not have more than one externally visible definition: AND TypeError: Error #1006: hitTestObject is not a function

I have 2 issues in this code.
The first is:
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
I've put multiple Actionscripts together to create this, i've seperated out the classes and am hoping to play this on a frame from a symbol.
and the second relates to:
Error #1006: hitTestObject is not a function
For this i'm trying to get the aagun/Sprayer to lose health then lives if the bugs touch it, but i'm not sure why it's saying it's not a function. Am I using the wrong words?
Thanks for your help, here's the code
package Shooter{
import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;
class Sprayer extends MovieClip{
const speed:Number = 150.0;
var lastTime:int; // animation time
function Sprayer() {
// initial location of gun
this.x = 275;
this.y = 340;
// movement
addEventListener(Event.ENTER_FRAME,moveGun);
}
function moveGun(event:Event) {
// get time difference
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// current position
var newx = this.x;
// move to the left
if (MovieClip(parent).leftArrow) {
newx -= speed*timePassed/1000;
}
// move to the right
if (MovieClip(parent).rightArrow) {
newx += speed*timePassed/1000;
}
// check boundaries
if (newx < 10) newx = 10;
if (newx > 540) newx = 540;
// reposition
this.x = newx;
}
// remove from screen and remove events
function deleteGun() {
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveGun);
}
}
}
package BigBug{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class bugs extends MovieClip {
var dx:Number; // speed and direction
var lastTime:int; // animation time
function bugs(side:String, speed:Number, altitude:Number) {
if (side == "left") {
this.x = -50; // start to the left
dx = speed; // fly left to right
this.scaleX = 1; // reverse
} else if (side == "right") {
this.x = -50; // start to the right
dx = -speed; // fly right to left
this.scaleX = 1; // not reverse
}
this.y = altitude; // vertical position
// choose a random plane
this.gotoAndStop(Math.floor(Math.random()*4+1));
// set up animation
addEventListener(Event.ENTER_FRAME,movePlane);
lastTime = getTimer();
}
function movePlane(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move plane
this.x += dx*timePassed/2000;
// check to see if off screen
if ((dx < 0) && (x < -50)) {
deletePlane();
} else if ((dx > 0) && (x > 350)) {
deletePlane();
}
}
}
}
package Missiles{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
class Bullets extends MovieClip {
var dx:Number; // vertical speed
var lastTime:int;
function Bullets(x,y:Number, speed: Number) {
// set start position
this.x = x;
this.y = y;
// get speed
dx = speed;
// set up animation
lastTime = getTimer();
addEventListener(Event.ENTER_FRAME,moveBullet);
}
function moveBullet(event:Event) {
// get time passed
var timePassed:int = getTimer()-lastTime;
lastTime += timePassed;
// move bullet
this.x += dx*timePassed/1000;
// bullet past top of screen
if (this.x < 0) {
deleteBullet();
}
}
// delete bullet from stage and plane list
function deleteBullet() {
MovieClip(parent).removeBullet(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveBullet);
}
}
}
package MainGame{
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.display.MovieClip;
import Missiles.Bullets;
import Shooter.Sprayer;
import BigBug.bugs;
public class AirRaid extends MovieClip {
private var aagun:Sprayer;
private var airplanes:Array;
private var buggood:Array;
private var bullets:Array;
public var leftArrow, rightArrow:Boolean;
private var nextGbug:Timer;
private var nextPlane:Timer;
private var shotsLeft:int;
private var shotsHit:int;
public function startAirRaid() {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
// create gun
aagun = new Sprayer();
addChild(aagun);
// create object arrays
buggood = new Array();
airplanes = new Array();
bullets = new Array();
// listen for keyboard
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// look for collisions
addEventListener(Event.ENTER_FRAME,checkForHits);
// start planes flying
setNextPlane();
setNextGbug();
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create plane
var p:bugs = new bugs(side,speed,altitude);
addChild(p);
airplanes.push(p);
// set time for next plane
setNextPlane();
}
public function setNextGbug() {
nextGbug = new Timer(1000+Math.random()*1000,1);
nextGbug.addEventListener(TimerEvent.TIMER_COMPLETE,newGbug);
nextGbug.start();
}
public function newGbug(event:TimerEvent) {
// random side, speed and altitude
if (Math.random() > .5) {
var side:String = "left";
} else {
side = "right";
}
var altitude:Number = Math.random()*50+20;
var speed:Number = Math.random()*150+150;
// create Gbug
var p:Good_bug = new Good_bug(side,speed,altitude);
addChild(p);
buggood.push(p);
// set time for next Gbug
setNextGbug();
}
// check for collisions
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=airplanes.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var Good_bugNum:int=buggood.length-1;Good_bugNum>=0;Good_bugNum--) {
if (bullets[bulletNum].hitTestObject(buggood[Good_bugNum])) {
buggood[Good_bugNum].GbugHit();
bullets[bulletNum].deleteBullet();
shotsHit--;
showGameScore();
break;
}
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
// key pressed
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = true;
} else if (event.keyCode == 39) {
rightArrow = true;
} else if (event.keyCode == 32) {
fireBullet();
}
}
// key lifted
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
}
}
// new bullet created
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullets = new Bullets(aagun.x,aagun.y,-300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: "+shotsHit);
showShots.text = String("Shots Left: "+shotsLeft);
}
// take a plane from the array
public function removePlane(plane:bugs) {
for(var i in airplanes) {
if (airplanes[i] == plane) {
airplanes.splice(i,1);
break;
}
}
}
// take a Gbug from the array
public function removeGbug(Gbug:Good_bug) {
for(var i in buggood) {
if (buggood[i] == Gbug) {
buggood.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullets) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
// game is over, clear movie clips
public function endGame() {
// remove planes
for(var i:int=airplanes.length-1;i>=0;i--) {
airplanes[i].deletePlane();
}
for(var i:int=buggood.length-1;i>=0;i--) {
buggood[i].deleteGbug();
}
airplanes = null;
buggood = null;
aagun.deleteGun();
aagun = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
removeEventListener(Event.ENTER_FRAME,checkForHits);
nextPlane.stop();
nextPlane = null;
nextGbug.stop();
nextGbug = null;
gotoAndStop("gameover");
}
}
}
1.
5006: An ActionScript file can not have more than one externally visible definition: Sprayer, bugs
As it says exactly: you can't have more than one public definition in a file. You have to either split the code to several files or move definitions, that you don't need public, out of the package.
This would be Ok in one file:
package
{
import flash.display.MovieClip;
// public is the default access modifier
public class Test1 extends MovieClip
{
public function Test1()
{
trace("test1");
var t2:Test2 = new Test2();
var t3:Test3 = new Test3();
}
}
}
// Test2 and Test3 are defined outside of the package, otherwise it wouldn't compile.
// These definitions will only be visible to code in this file.
import flash.display.MovieClip;
class Test2 extends MovieClip
{
public function Test2()
{
trace("test2");
}
}
class Test3 extends MovieClip
{
public function Test3()
{
trace("test3");
}
}
2.
Error #1006: hitTestObject is not a function
This usually means that hitTestObject() is not defined on the object (or it's ancestors) you are trying to call it from (although there could be different kinds of errors for that).
hitTestObject() is accessed in two ways in your code: airplanes.hitTestObject() and bullets[bulletNum].hitTestObject(). You will have to debug your code to see what is actually airplanes and bullets[bulletNum], what types they are and whether they inherit hitTestObject() method. You could at least trace() them.

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

Actionscript Loader Error #1009

I'm trying to make a basic loader that uses Splash.swf to then load myisogame.swf
I keep getting error #1009. It's a template we was given in class, originally the Splash.swf directed to Game.swf, but in the code below there is only one mention of where it directs to.
In the template Game.fla doesn't have any code in it.
Here is the Splash
package {
import flash.display.MovieClip;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFormat;
public class Splash extends MovieClip {
var myLoader:Loader;
var loadingAnim:LoadingAnimation;
var percentLoaded:TextField =new TextField();
public function Splash() {
// constructor code
myLoader = new Loader();
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
var blubox = new BluBox();
addChild(blubox);
blubox.x=200;
blubox.y=200;
loadingAnim = new LoadingAnimation();
addChild(loadingAnim);
loadingAnim.x=200;
loadingAnim.y=200;
loadingAnim.scaleX=0;
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0xFF0000;
format.size = 20;
format.underline = false;
percentLoaded.defaultTextFormat = format;
addChild(percentLoaded);
percentLoaded.x=200;
percentLoaded.y=230;
myLoader.load(new URLRequest("myisogame.swf"));
}
function onProgress(evt:ProgressEvent):void {
var nPercent:Number = Math.round((evt.bytesLoaded / evt.bytesTotal) * 100);
loadingAnim.scaleX = nPercent / 100;
percentLoaded.text = nPercent.toString() + "%";
trace("load%"+nPercent.toString());
}
function onComplete(evt:Event):void {
myLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
myLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
loadingAnim.x=1000;
addChild(myLoader);
}
function onIOError(evt:IOErrorEvent):void {
trace("IOError loading SWF");
}
}
}
5
6
7
8
11
12
13
14
20
25
26
MyIsoGame code
package {
import flash.display.MovieClip;
import as3isolib.display.scene.IsoScene;
import as3isolib.display.IsoView;
import as3isolib.display.scene.IsoGrid;
import as3isolib.graphics.Stroke;
import as3isolib.display.primitive.IsoBox;
import as3isolib.display.IsoSprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import eDpLib.events.ProxyEvent;
import as3isolib.geom.Pt;
import as3isolib.geom.IsoMath;
import as3isolib.graphics.SolidColorFill;
// before class
public class MyIsoGame extends MovieClip {
public var scene:IsoScene;
public var view:IsoView ;
public var CELLSIZE:int = 30;//------This is very important to remember cell size. This will affect placement of objects
var zoomFactor:Number = 1;////Zoom Factor heerrrreee--------------------
var s1:IsoSprite = new IsoSprite();
var wr:IsoSprite = new IsoSprite();
var wre:IsoSprite = new IsoSprite();
var g1:IsoSprite = new IsoSprite();
var b1:IsoSprite = new IsoSprite();
var b2:IsoSprite = new IsoSprite();
var b3:IsoSprite = new IsoSprite();
public function MyIsoGame() {
// constructor code
trace("hello from constructor");
scene = new IsoScene();
view = new IsoView();
view.setSize((stage.stageWidth), stage.stageHeight);
view.clipContent = true;
view.showBorder = false;
view.addScene(scene);
view.addEventListener(MouseEvent.MOUSE_DOWN, onStartPan, false, 0, true);
view.addEventListener(MouseEvent.MOUSE_WHEEL, onZoom, false, 0, true);
addChild(view);
var g:IsoGrid = new IsoGrid();
g.addEventListener(MouseEvent.CLICK, gridClick);
g.cellSize=30;
g.setGridSize(6,6);
g.y=0;
g.x=0;
g.gridlines = new Stroke(2,0x666666);
g.showOrigin = false;
scene.addChild(g);
g.addEventListener(MouseEvent.CLICK, grid_mouseHandler);
var box:IsoBox = new IsoBox();
box.setSize(10, 10, 10);
box.moveTo(50,50,0);
scene.addChild(box);
wr.setSize(30, 30, 30);
wr.moveTo(60, 0, 0);
wr.sprites=[new Wrecked()];
scene.addChild(wr);
wre.setSize(30, 30, 30);
wre.moveTo(30, 0, 0);
wre.sprites=[new Wrecked()];
scene.addChild(wre);
g1.setSize(30, 30, 30);
g1.moveTo(150, 150, 0);
g1.sprites=[new Gold()];
scene.addChild(g1);
b1.setSize(30, 30, 30);
b1.moveTo(120, 120, 0);
b1.sprites=[new Blue()];
scene.addChild(b1);
b2.setSize(30, 30, 30);
b2.moveTo(120, 150, 0);
b2.sprites=[new Blue()];
scene.addChild(b2);
b3.setSize(30, 30, 30);
b3.moveTo(150, 120, 0);
b3.sprites=[new Blue()];
scene.addChild(b3);
scene.render();
stage.addEventListener(MouseEvent.MOUSE_WHEEL,mouseWheel);///MOUSE WHEEL CONTROL
stage.addEventListener (KeyboardEvent.KEY_DOWN, keyboarddownlistener)
}
private function gridClick(event:ProxyEvent):void
{
var me:MouseEvent = MouseEvent(event.targetEvent);
var p:Pt = new Pt(me.localX, me.localY);
IsoMath.screenToIso(p);
y
}
private var panPt:Pt;
private function onStartPan(e:MouseEvent):void
{
panPt = new Pt(stage.mouseX, stage.mouseY);
view.removeEventListener(MouseEvent.MOUSE_DOWN, onStartPan);
view.addEventListener(MouseEvent.MOUSE_MOVE, onPan, false, 0, true);
view.addEventListener(MouseEvent.MOUSE_UP, onStopPan, false, 0, true);
}
private function onPan(e:MouseEvent):void
{
view.panBy(panPt.x - stage.mouseX, panPt.y - stage.mouseY);
panPt.x = stage.mouseX;
panPt.y = stage.mouseY;
}
private function boxClick(e:Event)
{
view.centerOnIso(e.target as IsoBox);
}
private function onStopPan(e:MouseEvent):void
{
view.removeEventListener(MouseEvent.MOUSE_MOVE, onPan);
view.removeEventListener(MouseEvent.MOUSE_UP, onStopPan);
view.addEventListener(MouseEvent.MOUSE_DOWN, onStartPan, false, 0, true);
}
private var zoomValue:Number = 1;
private function onZoom(e:MouseEvent):void
{
if(e.delta > 0)
zoomValue += 0.10;
if(e.delta < 0)
zoomValue -= 0.10;
view.currentZoom = zoomValue;
}
///----------------Grid Mouse Handler
public function grid_mouseHandler (evt:ProxyEvent):void
{
var mEvt:MouseEvent = MouseEvent(evt.targetEvent);
var pt:Pt = new Pt(mEvt.localX, mEvt.localY);
IsoMath.screenToIso(pt);
var roundedX:int = int(pt.x)/30;
var roundedY:int= int(pt.y)/30;
trace("transformed point = "+roundedX +","+roundedY);
///Code that allows things to be put down, located here.
var s:IsoSprite= new IsoSprite();
s.sprites=[new Base()];
s.setSize(30, 30, 30);//Varies via Cell size-
s.moveTo(roundedX*30, roundedY*30, 0);
scene.addChild(s);
scene.render();
}///------------------Grid Mouse Handler
public function mouseWheel (event:MouseEvent){
trace("The Delta value isss: " + event.delta);
//Get current view zoom
zoomFactor+=event.delta*0.04;
view.zoom(zoomFactor)
}
public function keyboarddownlistener(e:KeyboardEvent){
{//Screen-Movement Code
if (e.keyCode == 40)
{// The numbers represent the keyboard buttons
trace("Down Arrow")// I've left these trace commands so you can get a better idea of which one is what.-William 22/04/14
view.pan(0,5);
scene.render();
//Down arrow???
}
}
if (e.keyCode == 38)
{
trace("Up Arrow")
view.pan(0,-5);
scene.render();
//Up arrow???
}
if (e.keyCode == 37)
{
trace("Left Arrow")
view.pan(5,0);
scene.render();
//Left arrow???
}
if (e.keyCode == 39)
{
trace("Right Arrow")
view.pan(-5,0);
scene.render();
//Right arrow???
}
/////OBJECT MOVEMENT code- For moving the donut around
///-- I am going to be working on a version of this game where--
///- everything can be controlled via a Keyboard only -William 22/04/14
if (e.keyCode == 65)
{
trace("A Left <--")
//view.x+=15;//Alternate version
s1.moveBy(30,0,0)
scene.render();
//Left?
}
if (e.keyCode == 68)
{
trace("D Right -->")
//view.x-=15;//Alternate version
s1.moveBy(-30,0,0)
scene.render();
//Right?
}
if (e.keyCode == 83)
{
trace("S Down --v")
//view.x-=15;//Alternate version
s1.moveBy(0,30,0)
scene.render();
//Down?
}
if (e.keyCode == 87)
{
trace("W Up --^")
//view.x-=15;//Alternate version
s1.moveBy(0,-30,0)
scene.render();
//Up?
}
}
}
}
I tried the code you supplied (without the numbers at the bottom) and it worked just fine for me.
error #1009 is a runtime error when you use a variable that hasn't been defined yet. I would suggest debugging from Flash Pro (ctrl + shift +enter) and let it show you where it breaks.
In your FLA, you said there is no code, but in the properties panel you do see the class field with "Splash" in it right? that is what links the class to the FLA.
It is possible that the runtime error you are seeing is not in the Splash class but in either BluBox or LoadingAnimation. Do those have class files? If not, take a look in the Library and you'll have two movie clips that are exported for actionScript with those names. Check in them to see if there might be some framescript.