How can make my game support touch screen? - actionscript-3

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

Related

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.

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?

Movieclip not moving on its own

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.

Actionscript 3 Making the character to Jump

I am making a platformer game. But I am having issue because whenever I pressed the spacebar to jump, the character will stuck in the mid-air. However, I can resolved the problem by holding spacebar and the character will land.
The issue is at mainJump() located inside Boy class.
I seen many people solved the problem by using action timeline, but my main problem is, are there anyway I can solve the problem by using an external class?
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 = 5;
//whether or not the main guy is jumping
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 theCharacter:MovieClip;
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)
{
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 (currentY >= stage.stageHeight - MovieClip(this).height)
{
mainJumping = false;
currentY = stage.stageHeight - MovieClip(this).height;
}
}
}
}
First of all, formalize your code, eliminating sassy things like 'pressTheDamnKey,' which doesn't even describe the function very well because a function cannot press a key. That is an event handler and should be named either keyDownHandler or onKeyDown, nothing else.
Secondly, you rarely want to do any actual work in event handlers beyond the immediate concerns of the event data. Instead call out to the function which does the actual work. A handler handles the event, then calls the code which does the work. This separates out concerns nicely for when you want something else to be able to also make the little boy animate besides the enterFrameHandler, like perhaps a mouse.
I can imagine your trace log is getting filled up pretty quickly with "Score" lines since your timer is firing 100 times a second (10 milliseconds per). I would change that to not fire on a timer, but to be refreshed when the score actually changes.
The problem with the jumping, aside from spaghetti code, is that you are basing his movements upon whether the key is pressed or not by saving the state of the key press in a variable and having him continually inspect it. This is bad for a couple of reasons: 1. he should not need to reach out to his environment for information, it should be given to him by whatever object owns him or by objects that are responsible for telling him and 2. It requires you to continually hold down the spacebar or he will stop moving, since he checks to see if it is being held down (see problem 1).
I will address all these issues below, leaving out the scoring, which is another matter altogether.
package
{
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.*;
// Sprite is preferred if you are not using the timeline
public class Application extends Sprite
{
private var boy:Boy;
public function Application()
{
boy = new Boy();
addChild(boy);
boy.x = 600; // set these here, not in the boy
boy.y = 540;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler );
}
public function keyDownHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case 32: boy.jump();
break;
case 37: boy.moveLeft();
break;
case 39: boy.moveRight();
break;
default:
// ignored
break;
}
}
public function keyUpHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
// ignored for jumping (32)
case 37: // fall through
case 39: boy.stop();
break;
default:
// ignored
break;
}
}
}//class
}//package
package
{
import flash.display.*;
import flash.events.*;
// It is assumed that there is an asset in the library
// that is typed to a Boy, thus it will be loaded onto
// the stage by the owner
public class Boy extends Sprite
{
private var horzSpeed :Number = 0;
private var vertSpeed :Number = 0;
private var floorHeight :Number;
private var jumpHeight :Number;
private var amJumping :Boolean = false;
public function Boy()
{
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
public function moveLeft():void
{
horzSpeed = -1;
}
public function moveRight():void
{
horzSpeed = 1;
}
public function stop():void
{
horzSpeed = 0;
}
public function jump():void
{
if (amJumping) return;
floorHeight = y;
jumpHeight = floorHeight + 20;
vertSpeed = 2;
amJumping = true;
animateJump();
}
private function enterFrameHandler(event:Event):void
{
animate();
}
private function animate():void
{
x += horzSpeed;
if( amJumping )
{
animateJump();
}
}
// Doing a simple version for this example.
// If you want an easier task of jumping with gravity,
// I recommend you employ Greensock's superb
// TweenLite tweening library.
private function animateJump():void
{
y += vertSpeed;
if( y >= jumpHeight )
{
y = jumpHeight;
vertSpeed = -2;
}
else if( y <= floorHeight )
{
y = floorHeight;
amJumping = false;
}
}
}//class
}//package
Another way to approach this, and probably the better way long-term, is for the boy to not even be responsible for moving himself. Instead, you would handle that in the parent, his owner or some special Animator class that is responsible for animating things on schedule. In this even more encapsulated paradigm, the boy is only responsible for updating his own internal look based upon the outside world telling him what is happening to him. He would no longer handle jumping internally, but instead would be responsible for doing things like animating things he owns, like his arms and legs.
You've got a mainJumping variable that is only true while the jump is running. Why not just use that?
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}

Several errors "Access of undefined property"

So I have this pretty basic code in my document class:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.*;
import flash.events.MouseEvent;
import flash.display.Stage;
import flash.display.MovieClip;
public class Main extends Sprite
{
//Properties
public var circle:Circle;
public var vx:Number;
public var vy:Number;
addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);
addEventListener(Event.ENTER_FRAME, onEnter);
public function addedToStageHandler(event:Event):void
{
}
public function Main()
{
super();
init();
}
public function init():void
{
vx = 0;
vy = 0;
circle = new Circle(35, 0x0066FF);
stage.addChild(circle);
circle.x = 50;
circle.y = 50;
}
public function onKeyboardDown(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.LEFT:
vx = -5;
break;
case Keyboard.RIGHT:
vx = 5;
break;
case Keyboard.UP:
vy = -5;
break;
case Keyboard.DOWN:
vy = 5;
break;
}
}
public function onKeyboardUp(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.LEFT:
vx = 0;
break;
case Keyboard.RIGHT:
vx = 0;
break;
case Keyboard.UP:
vy = 0;
break;
case Keyboard.DOWN:
vy = 0;
break;
}
}
public function onEnter(event:Event):void
{
circle.x += vx;
circle.y += vy;
}
}
}
The problem is that I keep getting errors that to a beginner don't make any sense:
"Call to a possibly undefined method addEventListener." x 3
"Access of undefined property onEnter."
"Access of undefined property onKeyboardUp."
"Access of undefined property onKeyboardDown."
I really don't understand this issue. How can AS3 not recognize addEventListener? As well, I did have it so my event listeners were added to the stage "stage.addEventListener" and it wasn't recognizing the stage either. Can somebody push me in the right direction with this issue? Thanks!
It's logic because you'll have to place the eventListeners inside the ´init´ method or Class constructor.
public function init():void
{
addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);
addEventListener(Event.ENTER_FRAME, onEnter);
vx = 0;
vy = 0;
circle = new Circle(35, 0x0066FF);
stage.addChild(circle);
circle.x = 50;
circle.y = 50;
}
If not the listeners are placed outside the class scope, and therefor not recognized.
Good luck!
All in all your code is almost there you just need a little bit better understanding on how the display list works.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.*;
import flash.events.MouseEvent;
import flash.display.Stage;
import flash.display.MovieClip;
public class Main extends Sprite
{
//Properties
public var circle:Circle;
public var vx:Number;
public var vy:Number;
// we can not do function calls like this in the class declaration area
// so we move these listeners to a function
// addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
// addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);
// addEventListener(Event.ENTER_FRAME, onEnter);
public function Main()
{
super();
this.init();
}
public function init():void
{
// the "this" keyword means we are scoping it to this class instance
this.addEventListener( EVENT.ADDEDTOSTAGE, addedToStageHandler)
// using "this" is good practice and will help make your code more readable
this.vx = 0;
this.vy = 0;
this.circle = new Circle(35, 0x0066FF);
stage.addChild(circle);
this.circle.x = 50;
this.circle.y = 50;
}
public function addedToStageHandler(event:Event):void
{
// doing addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
// will set the scope for this listener to this class
// you want to target the stage. And since we are waiting for ADDEDTOSTAGE
// to trigger we know we are on the stage.
// the only time we can access stage is if we are on the display list.
// clean up the listener since we do not need it anymore
this.removeEventListener( EVENT.ADDEDTOSTAGE, addedToStageHandler)
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyboardUp);
stage.addEventListener(Event.ENTER_FRAME, onEnter);
}
public function onKeyboardDown(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.LEFT:
this.vx = -5;
break;
case Keyboard.RIGHT:
this.vx = 5;
break;
case Keyboard.UP:
this.vy = -5;
break;
case Keyboard.DOWN:
this.vy = 5;
break;
}
}
public function onKeyboardUp(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case Keyboard.LEFT:
this.vx = 0;
break;
case Keyboard.RIGHT:
this.vx = 0;
break;
case Keyboard.UP:
this.vy = 0;
break;
case Keyboard.DOWN:
this.vy = 0;
break;
}
}
public function onEnter(event:Event):void
{
this.circle.x += this.vx;
this.circle.y += this.vy;
}
}
}