Movieclip not moving on its own - actionscript-3

I have a game. (Feel to download it here)
In my game, you may notice that the man doesn't move on its own. You have to click the screen once to get the man to move left and right with the arrow keys.
My Main.as:
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.DisplayObjectContainer;
import flash.text.TextField;
import flash.events.MouseEvent;
import flash.display.Graphics;
import flash.display.Sprite;
import flash.geom.ColorTransform;
import flash.text.TextFormat;
import flash.text.engine.TextBaseline;
public dynamic class Main extends MovieClip
{
// classes
private var _physics:Physics;
private var _timer:Timer;
var interval_timer:TextField = new TextField();
private var startTime:int;
private var diff:int;
private var _timer2:Timer
private var _stage:MovieClip = container;
private var _frame:int;
private var fade:Number = 1.0;
private var fadeAmount:Number = 0.01;
private var _timer3:Timer = new Timer(25);
private var retval:Boolean = false;
var survive:TextField = new TextField();
var survivedTime:Number;
var isRight:Boolean=false
var isLeft:Boolean=false
var isUp:Boolean=false
var isDown:Boolean=false
var pause:TextField = new TextField();
var pausedes:TextField = new TextField();
public function Main()
{
_physics = new Physics(container);
_physics.enable();
_timer = new Timer(500);
_timer.addEventListener(TimerEvent.TIMER, timerFunction);
_timer.start();
start.addEventListener(MouseEvent.CLICK, buttonClickHandler);
credits.addEventListener(MouseEvent.CLICK, buttonClickHandler2);
}
// the event listeners
private function update(e:Event):void
{
var currentTime:int = getTimer();
var _ballArray:Array = _physics._ballArray;
var tempBall1:Ball;
var i:int;
//check if we hit top
if (((man.x - man.width / 2) <= _physics._minX))
{
man.x += 7;
}
else if (((man.x + man.width / 2) >= _physics._maxX))
{
man.x -= 7;
}
for (i = 0; i < _ballArray.length; i++)
{
// save a reference to ball
tempBall1 = _ballArray[i] as Ball;
if(_physics.hitTestCircle(tempBall1, man))
{
man.gotoAndStop(2);
retval = true;
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
stage.removeEventListener(KeyboardEvent.KEY_UP, upKey);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.removeEventListener(Event.ENTER_FRAME, move);
}
if(retval)
{
_physics.disable();
_timer2.stop();
survivedTime = diff;
_timer3.addEventListener(TimerEvent.TIMER, darken);
_timer3.start();
stage.removeEventListener(Event.ENTER_FRAME, update);
_physics._ballArray = [];
//trace("you died!");
retval = false;
}
}
diff = currentTime*0.001 - startTime*0.001;
interval_timer.text = String(diff);
}
private function darken(e:TimerEvent):void
{
fade-= fadeAmount;
if(fade < 0.0)
{
fade = 0.0;
_timer3.removeEventListener(TimerEvent.TIMER, darken);
_timer3.stop();
endGame();
}
container.transform.colorTransform = new ColorTransform(fade, fade, fade, 1.0, 0, 0, 0, 0);
}
private function downKey(event:KeyboardEvent)
{
if(event.keyCode==39)
{
isRight=true;
}
if(event.keyCode==37)
{
isLeft=true;
}
if(event.keyCode==38)
{
isUp=true
}
if(event.keyCode==40)
{
isDown=true
}
}
private function upKey(event:KeyboardEvent){
if(event.keyCode==39){
isRight=false}
if(event.keyCode==37){
isLeft=false}
if(event.keyCode==38){
isUp=false}
if(event.keyCode==40){
isDown=false}
}
private function move(e:Event)
{
if(isRight==true)
{
man.x +=5;
}
if(isLeft==true)
{
man.x -= 5;
}
}
private function frame(e:Event):void
{
_frame = currentFrame;
if(_frame == 25)
{
startGame();
}
}
private function startGame():void
{
_physics._ballArray = [];
stage.removeEventListener(Event.ENTER_FRAME, frame);
//stage.removeEventListener(Event.ENTER_FRAME, startGame);
stage.removeEventListener(Event.ENTER_FRAME, _physics.remove);
_physics.enable();
// enable physics simulation
_timer2 = new Timer(500);
_timer2.addEventListener(TimerEvent.TIMER, timerFunction);
_timer2.start();
stage.addEventListener(Event.ENTER_FRAME, update);
interval_timer.y = 18;
interval_timer.x = 500;
addChild(interval_timer);
startTime = getTimer();
}
private function endGame()
{
var myFormat:TextFormat = new TextFormat();
myFormat.size = 23;
survive.defaultTextFormat = myFormat;
gotoAndStop(26);
survive.x = 179.45;
survive.y = 177.90;
survive.textColor = 0xFFFFFF;
survive.text = String(survivedTime + " secs");
addChild(survive);
stage.addEventListener(Event.ENTER_FRAME, _physics.remove);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
stage.removeEventListener(KeyboardEvent.KEY_UP, upKey);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.removeEventListener(Event.ENTER_FRAME, move);
mainmenu.addEventListener(MouseEvent.CLICK, buttonClickHandler5);
retry.addEventListener(MouseEvent.CLICK, buttonClickHandler6);
_physics._ballArray = [];
}
private function onKeyEvent(e:KeyboardEvent):void
{
if (stage.frameRate == 20)
{
if (e.keyCode == 80)
{
stage.frameRate = 8;
stage.removeEventListener(Event.ENTER_FRAME, update);
pauseGame();
}
}
else if (stage.frameRate == 8)
{
if (e.keyCode == 80)
{
stage.frameRate = 20;
stage.addEventListener(Event.ENTER_FRAME, update);
unpause();
}
}
}
private function pauseGame():void
{
_physics.disable();
_timer2.stop();
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
stage.removeEventListener(KeyboardEvent.KEY_UP, upKey);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.removeEventListener(Event.ENTER_FRAME, move);
var myFormat:TextFormat = new TextFormat();
var myFormat2:TextFormat = new TextFormat();
myFormat.size = 30;
myFormat2.size = 15;
pause.defaultTextFormat = myFormat;
pausedes.defaultTextFormat = myFormat2;
pause.x = 239.95;
pause.y = 165.90;
pause.textColor = 0x000000;
pausedes.x = 221.8;
pausedes.y = 205.45;
pausedes.width = 130.2;
pausedes.textColor = 0x000000;
pause.text = String("Paused");
pausedes.text = String("Press P to Unpause");
addChild(pause);
addChild(pausedes);
}
private function unpause():void
{
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.addEventListener(Event.ENTER_FRAME, move);
_physics.enable();
_timer2.start();
removeChild(pause);
removeChild(pausedes);
}
public function timerFunction(e:TimerEvent):void
{
_physics.createBalls(1);
}
//start button
private function buttonClickHandler(event:MouseEvent):void
{
gotoAndStop(3);
ok.addEventListener(MouseEvent.CLICK, buttonClickHandler4);
_physics.disable();
_timer.stop();
_timer.removeEventListener(TimerEvent.TIMER, timerFunction);
stage.addEventListener(Event.ENTER_FRAME, _physics.remove);
_physics._ballArray = [];
}
//credits button
private function buttonClickHandler2(event:MouseEvent):void
{
gotoAndStop(2);
stage.addEventListener(Event.ENTER_FRAME, _physics.remove);
_physics.disable();
_timer.removeEventListener(TimerEvent.TIMER, timerFunction);
_timer.stop();
back.addEventListener(MouseEvent.CLICK, buttonClickHandler3);
_physics._ballArray = [];
}
//back button
private function buttonClickHandler3(event:MouseEvent):void
{
gotoAndStop(1);
_physics.enable();
_timer.addEventListener(TimerEvent.TIMER, timerFunction);
stage.removeEventListener(Event.ENTER_FRAME, _physics.remove);
_timer.start();
start.addEventListener(MouseEvent.CLICK, buttonClickHandler);
credits.addEventListener(MouseEvent.CLICK, buttonClickHandler2);
_physics._ballArray = [];
}
//ok button
private function buttonClickHandler4(event:MouseEvent):void
{
stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.addEventListener(Event.ENTER_FRAME, move);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
gotoAndPlay(4);
stage.addEventListener(Event.ENTER_FRAME, frame);
_physics._ballArray = [];
//stage.addEventListener(Event.ENTER_FRAME, startGame);
}
//main menu button
private function buttonClickHandler5(event:MouseEvent):void
{
gotoAndStop(1);
container.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0, 0, 0);
removeChild(survive);
removeChild(interval_timer);
_physics.enable();
_timer.addEventListener(TimerEvent.TIMER, timerFunction);
stage.removeEventListener(Event.ENTER_FRAME, _physics.remove);
_timer.start();
start.addEventListener(MouseEvent.CLICK, buttonClickHandler);
credits.addEventListener(MouseEvent.CLICK, buttonClickHandler2);
_physics._ballArray = [];
fade = 1.0;
fadeAmount = 0.01;
}
//retry button
private function buttonClickHandler6(event:MouseEvent):void
{
container.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0, 0, 0);
removeChild(survive);
removeChild(interval_timer);
gotoAndPlay(4);
stage.addEventListener(Event.ENTER_FRAME, frame);
stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
stage.addEventListener(Event.ENTER_FRAME, move);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);
_physics._ballArray = [];
fade = 1.0;
fadeAmount = 0.01;
man.x = 286.65;
man.y = 391.85;
man.gotoAndStop(1);
}
}
}
This is the file I use to make the man move. Where is the code do I change to make the game work so the man moves the after "Go!", and you don't have to click the screen.
Another question I have is: When you press "P", you can pause the game. However, you may notice after unpausing the game by pressing "P" again, the timer is off by the number of seconds you were paused. This code also is the code for the timer. What do I change in the code to make the timer run correctly, meaning that after unpausing the game, it doesn't skip the number of the seconds you were paused, instead it continues from where it left off.

This is getting too long a comment thread for this question. After you call buttonClickHandler4, your keyboard events should be functioning.
Set debug points, or trace statements, to see if buttonClickHandler4 is being called. Add the same to make sure downKey and move are being called. This should narrow down the problem.

EDIT: I figured out the problem using this link: http://www.trainingtutorials101.com/2010/10/keyboard-events-wont-work-unless-user.html
I had to use the command stage.focus = this to focus the stage on my movieclip man, so that way it could listen for keyboard events without my mouse clicking the screen.
And to remove the yellow rectangle around the man I used the command stage.stageFocusRect = false.
Thanks to #dhc and #Vesper for all of their help.

Related

How can make my game support touch screen?

I have done a wheel game from a tutorial. The problem is the game works perfectly with a mouse but does not work on touch screens. I don't know how to manipulate it to transform the game.
How can I adapt the game to function with touch screens?
package
{
import flash.display.Sprite;
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.events.Event;
import com.greensock.TweenMax;
public final class Main extends Sprite
{
private var speed:Number = 0;
private var paddles:Vector.<Sprite> = new Vector.<Sprite>();
private var line:Shape;
private var lastPaddle:String;
public final function Main():void
{
paddles.push(wheel.p1, wheel.p2, wheel.p3, wheel.p4, wheel.p5, wheel.p6, wheel.p7, wheel.p8, wheel.p9, wheel.p10);
listeners('add');
}
private final function listeners(action:String):void
{
if(action == 'add')
{
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDraw);
stage.addEventListener(MouseEvent.MOUSE_UP, spinWheel);
}
else
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, startDraw);
stage.removeEventListener(MouseEvent.MOUSE_UP, spinWheel);
}
}
private final function startDraw(e:MouseEvent):void
{
line = new Shape();
addChild(line);
line.graphics.moveTo(mouseX, mouseY);
line.graphics.lineStyle(8, 0x000000, 0.3);
stage.addEventListener(MouseEvent.MOUSE_MOVE, drawLine);
}
private final function drawLine(e:MouseEvent):void
{
line.graphics.lineTo(mouseX, mouseY);
}
private final function spinWheel(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, drawLine);
listeners('rm');
speed = line.height * 0.1;
removeChild(line);
line = null;
stage.addEventListener(Event.ENTER_FRAME, spin);
}
private final function spin(e:Event):void
{
/* Rotate Wheel */
wheel.rotationZ += speed;
/* Detect Value */
for(var i:int = 0; i < 10; i++)
{
if(indicator.hArea.hitTestObject(paddles[i]))
{
lastPaddle = paddles[i].name;
}
}
/* Decrease speed */
speed -= 0.1;
/* Remove lIstener and reset speed when wheel stops */
if(speed <= 0)
{
stage.removeEventListener(Event.ENTER_FRAME, spin);
speed = 10;
run(lastPaddle);
listeners('add');
}
}
function run(action:String):void
{
switch(action)
{
case 'p1':
myText.text = "text 10";
break;
case 'p2':
myText.text = "text 25";
break;
case 'p3':
myText.text = "text 20";
break;
case 'p4':
myText.text = "text 50";
break;
case 'p5':
myText.text = "text 30";
break;
case 'p6':
myText.text = "text 75";
break;
case 'p7':
myText.text = "text 40";
break;
case 'p8':
myText.text = "text 100";
break;
case 'p9':
myText.text = "text 50";
break;
case 'p10':
myText.text = "text 125";
break;
}
}
}
}
first of all set in stage :
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT
after that
just replace MouseEvent to TouchEvent and replace MOUSE_DOWN to TOUCH_BEGIN and
MOUSE_UP to TOUCH_END. after that you must change MouseEvent in event handler to TouchEvent
and if you have using MOUSE_MOVE chenge that to TOUCH_MOVE
private final function listeners(action:String):void
{
if(action == 'add')
{
stage.addEventListener(TouchEvent.TOUCH_BEGIN, startDraw);
stage.addEventListener(TouchEvent.TOUCH_END, spinWheel);
}
else
{
stage.removeEventListener(TouchEvent.TOUCH_END, startDraw);
stage.removeEventListener(TouchEvent.TOUCH_BEGIN, spinWheel);
}
}

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

Can't remove object from stage

I have a problem. I am trying to make a copter game in Adobe Flash with ActionScript 3.0, but now the game works, but the obstacles can't be removed from stage. The obstacles are still going miles out of the stage. How can I remove the obstacles?? and same problem if you are game over, if you are game over the event end, but the last spawned obstacles you see still and aren't removed. And how can I make the obstacles go faster after a period of time??
There are standing some dutch words in it, such as 'hoeSpelen' that is for instructions text en 'af' is for the gameover text and 'tijd' = time and 'balkje' = obstacles.
I hope you can help me.
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.utils.getTimer;
import flash.events.Event;
public class iCopter extends MovieClip
{
private var copter : Copter = null;
private var gameover : GameOver = null;
private var balkje : Balkje = null;
private var tijd : int
var score = 0;
var highscore = 0;
public function onStartButton(event:MouseEvent)
{
startiCopter()
}
public function iCopter()
{
startButton.addEventListener(MouseEvent.CLICK, onStartButton);
af.visible = false
output.visible = false
hscore.visible = false
}
public function startiCopter()
{
removeChild(startButton);
removeChild(hoeSpelen);
removeChild(af);
score = 0
icopterlogo.visible = false
output.visible = true
hscore.visible = true
copter = new Copter();
copter.x = 100;
copter.y = 200;
addChild(copter);
tijd = getTimer();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
public function onEnterFrame(event:Event)
{
var now:int = getTimer();
if (now - tijd > 1250)
{
var balkje = new Balkje();
balkje.x = 350;
balkje.y = Math.random() * 150;
addChild (balkje);
tijd = now
score = score + 10;
output.text = "score: "+score;
if (balkje.x <= -10) //don't work.
{ //don't work.
removeChild (balkje); //don't work.
} //don't work.
}
addEventListener(Event.ENTER_FRAME, botsing);
}
function botsing (event:Event)
{
for (var i = 0; i < numChildren; i++)
{
if (getChildAt(i) is Balkje || getChildAt(i) is Vloer)
{
var b = getChildAt(i) as MovieClip;
if (b.hitTestObject(copter))
{
removeChild (copter);
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
var gameover = new GameOver();
addChild(af);
af.visible = true
addChild(hoeSpelen);
addChild(startButton);
if (score > highscore)
{
highscore = score
hscore.text = "highscore: "+highscore;
}
}
}
}
}
}
}
Here are the scripts for the copter and obstacle
copter:
muisKlik = mouseClick
muisDruk = mousePush
muisOmhoog = mouseUp
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class Copter extends MovieClip
{
var vy : Number = 0;
var muisKlik : Boolean = false;
public function Copter()
{
vy = 5;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(event:Event)
{
stage.addEventListener(MouseEvent.MOUSE_DOWN, muisDruk);
stage.addEventListener(MouseEvent.MOUSE_UP, muisOmhoog);
}
public function onEnterFrame(event:Event)
{
if (muisKlik == true)
{
y -= vy;
}
else
{
y += vy;
}
}
public function muisDruk (event:MouseEvent)
{
muisKlik = true
}
public function muisOmhoog (event:MouseEvent)
{
muisKlik = false
}
}
}
obstacle:
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class Balkje extends MovieClip
{
var vx : Number = 1;
public function Balkje()
{
vx = 5;
addEventListener( Event.ENTER_FRAME, onEnterFrame );
}
public function onEnterFrame( event:Event )
{
x -= vx;
}
}
}
Not tested - probably full of errors, and I haven't done AS3 in a while:
When you initialize obstacles, pass in the stage object (not sure if this is the best practice)
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Balkje extends MovieClip
{
var vx : Number = 1;
public function Balkje()
{
vx = 5;
if(!stage){
//if stage isn't populated yet, wait for it
this.addEventListner(Event.ADDED_TO_STAGE,addedToStage);
}else{
init();
}
}
private function addedToStage(e:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE,addedToStage);
init();
}
protected function init():void {
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
public function onEnterFrame( event:Event )
{
x -= vx;
//check x
if(this.x + this.width <= 0 || this.x >= stage.stageWidth) {
if(this.parent) this.parent.remmoveChild(this);
removeEventListener( Event.ENTER_FRAME, onEnterFrame );
}
}
}
}
Again, not tested (is stage.stageWidth correct to get the stage width?) but you get the idea. Check the x of the object, if it is outside the visible stage remove it from its parent (I just put this.parent because you didn't add the obstacle to the stage).
Also, why do you add event listener to ENTER_FRAME in a function called by ENTER_FRAME?

Move the circle in as3

I already have the graphic with image on the screen and I wanted to it to move when I pressed the arrows on keyboard.
But it seems the listener is not running and there is no error.
Here is the code:
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.display.BitmapData;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.net.URLRequest;
/**.
* ....
* #author Kaoru
*/
[SWF(width = '800', height = '600', backgroundColor = '#000000', frameRate = '24')]
public class GameManager extends Sprite
{
var myBitmap:BitmapData;
var imgLoader:Loader;
var circle:Sprite;
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function drawImage(e:Event):void
{
myBitmap = new BitmapData(imgLoader.width, imgLoader.height, false);
myBitmap.draw(imgLoader);
circle.graphics.beginBitmapFill(myBitmap, null, true);
circle.graphics.drawCircle(50, 50, 10);
circle.graphics.endFill();
addChild(circle);
}
private function onKeyDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
{
circle.x += 5;
}
else if (e.keyCode == Keyboard.RIGHT)
{
circle.x -= 5;
}
if (e.keyCode == Keyboard.UP)
{
circle.y += 5;
}
else if (e.keyCode == Keyboard.DOWN)
{
circle.y -= 5;
}
}
}
}
You need to add it to stage like so,
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
I have modified your code like so:
Always check for ADDED_TO_STAGE first and then proceed,
public function GameManager():void
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); //This line is modified
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
Have you tried to add your listener on the stage directly ?
So that this
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
Becomes this
public function GameManager():void
{
circle = new Sprite();
imgLoader = new Loader();
imgLoader.load(new URLRequest("../lib/fira_front.png"));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}

AS3 - CS6 - Incorect number of arguments

I'm trying to compile my 2D game to test it and I'm getting this error: \Main.as, Line 32 1136: Incorrect number of arguments. Expected 2.
Line 32 contains this code var enemy:Enemy = new Enemy(null);
Any help is always appreciated, thanks everyone.
Code associated with the error (I can post the rest if needed):
Main.as
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
public var player:Player;
public var enemy:Enemy;
public var bulletList:Array = [];
public var mousePressed:Boolean = false; //keeps track of whether the mouse is currently pressed down
public var delayCounter:int = 0; //this adds delay between the shots
public var delayMax:int = 7; //change this number to shoot more or less rapidly
public var enemies:Array = [];
public function Main():void
{
player = new Player(stage, 320, 240);
stage.addChild(player);
//stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true); //remove this
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
for(var numBaddies=0; numBaddies<6;numBaddies++){
var enemy:Enemy = new Enemy(null);
enemy.x = numBaddies*50;
enemy.y = numBaddies*50
stage.addChild(enemy);
enemies.push(enemy);
}
}
public function loop(e:Event):void
{
if(mousePressed) // as long as the mouse is pressed...
{
delayCounter++; //increase the delayCounter by 1
if(delayCounter == delayMax) //if it reaches the max...
{
shootBullet(); //shoot a bullet
delayCounter = 0; //reset the delay counter so there is a pause between bullets
}
}
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
/*for(var h = 0; h<bulletList.length; ++h)
{
if(bulletList[h].hitTestObject(this)){
trace("player hit by baddie " + h);
}
}*/
for(var u:int=0; u<enemies.length; u++) {
Enemy(enemies[u]).moveTowards(player.x, player.y);
}
}
public function mouseDownHandler(e:MouseEvent):void //add this function
{
mousePressed = true; //set mousePressed to true
}
public function mouseUpHandler(e:MouseEvent):void //add this function
{
mousePressed = false; //reset this to false
}
public function shootBullet():void //delete the "e:MouseEvent" parameter
{
var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation, enemies);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true);
bulletList.push(bullet);
stage.addChild(bullet);
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved);
bulletList.splice(bulletList.indexOf(e.currentTarget),1);
}
}
}
Enemy.as
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Enemy extends MovieClip {
public var bullets:Array;
public var stageRef:Stage;
private var enemyPositionX, enemyPositionY,xDistance,yDistance,myRotation:int;
public function Enemy(stageRef:Stage, bulletList:Array) {
// constructor code
bullets = bulletList;
this.stageRef = stageRef;
}
public function moveTowards(playerX:int, playerY:int){
xDistance = this.x - playerX;
yDistance = this.y - playerY;
myRotation = Math.atan2(yDistance, xDistance);
this.x -= 3 * Math.cos(myRotation);
this.y -= 3 * Math.sin(myRotation);
}
private function removeSelf():void
{
//removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
As you said, error is pointing to:
var enemy:Enemy = new Enemy(null);
and Enemy constructor is:
public function Enemy(stageRef:Stage, bulletList:Array){
So you are missing 2nd parameter - bulletList.