Need help fixing player jumping diagonally Flash CS4 - actionscript-3

I can't figure out why when I try and get my player to jump diagonally by pressing the right and up arrow key it does nothing, I've used trace to see if anything was happening and nothing was when they were used together.
Up won't work by itself or with right but when right is by itself it works.
player is named hero, platforms are named platform, platform2, platform3 etc
platforms are in the platform layer
stop();
var gravity:Number=5; //Very important, allows player to fall
var movex:Number=0; // Moving players X
// Moving player
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveHero);
var speed=10;
function moveHero(event:KeyboardEvent) {
if (event.keyCode==Keyboard.LEFT) {
hero.x-=speed;
hero.play();
}
if (event.keyCode==Keyboard.RIGHT) {
hero.x+=speed;
hero.play();
}
}
hero.addEventListener(Event.ENTER_FRAME, testCollision2);
// Allowing player to jump when on platform
function testCollision2(e: Event) {
//Allowing player to jump when on platform continued
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveHeroUP);
function moveHeroUP(event:KeyboardEvent) {
if (hero.hitTestObject(platform) && event.keyCode==Keyboard.UP) {
gravity=-50;
hero.y=hero.y+gravity;
} else if (hero.hitTestObject(platform2) && event.keyCode==Keyboard.UP) {
gravity=-50;
hero.y=hero.y+gravity;
} else if (hero.hitTestObject(platform4) && event.keyCode==Keyboard.UP) {
gravity=-50;
hero.y=hero.y+gravity;
}
if(hero.hitTestObject(platform) && event.keyCode==Keyboard.UP && event.keyCode==Keyboard.RIGHT){
movex = 20;
hero.x = hero.x + movex;
gravity =-50;
hero.y = hero.y + gravity;
}
}
I'm trying to get the player to jump in the code chunk at the very end
Flash CS4
AS3

To start, let's go through how you've set up this code and explain what's happening.
You have this line:
hero.addEventListener(Event.ENTER_FRAME, testCollision2);
Which is saying, every frame tick that hero exists, run the function testCollision2. Frame tick here doesn't relate to timeline frames, it relates to the frame rate of your application. So if that is set to 12, that function will run 12 times every second.
Inside testCollision2, you add another listener:
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveHeroUP);
and create an inline function called moveHeroUP. So every frame tick, you create a new function, and attach it to a key down event. So (assuming 12 frames per second) 5 seconds into your application, you'll have 60 keyboard listeners all doing the same thing. This is also a memory leak (as you keep creating a new function every frame), so eventually your program will crash.
To get to the actual question, a keyboard event is tied to one specific key. This means the event's keyCode is only ever one key (the key that triggered the event). So doing something like (event.keyCode==Keyboard.UP && event.keyCode==Keyboard.RIGHT) will always be false because event.keyCode only ever holds one value.
A common approach to your situation, is to have one global key down and key up listener. Then use a dictionary to store which keys are currently down:
//create just one key down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
//create a dictionary to store key presses
var keyboardDown:Dictionary = new Dictionary();
function keyDownHandler(e:KeyboardEvent):void {
keyboardDown[e.keyCode] = true;
}
function keyUpHandler(e:KeyboardEvent):void {
keyboardDown[e.keyCode] = false;
}
What you're doing here, is when a key down event fires, you set the value in the dictionary to true (with the keycode as the dictionary key), then on the key up event you set it to false.
Now, in your ENTER_FRAME handler, you use the dictionary values to check for key combinations:
hero.addEventListener(Event.ENTER_FRAME, moveHero);
function moveHero(event:Event) {
//DO ALL YOUR MOVEMENTS IN ONE ENTER FRAME FUNCTION
if (keyboardDown[Keyboard.LEFT]) {
hero.x-=speed;
hero.play();
}
if (keyboardDown[Keyboard.RIGHT]) {
hero.x+=speed;
hero.play();
}
if (hero.hitTestObject(platform) && keyboardDown[Keyboard.UP]) {
gravity=-50;
hero.y=hero.y+gravity;
} else if (hero.hitTestObject(platform2) && keyboardDown[Keyboard.UP]) {
gravity=-50;
hero.y=hero.y+gravity;
} else if (hero.hitTestObject(platform4) && keyboardDown[Keyboard.UP]) {
gravity=-50;
hero.y=hero.y+gravity;
}
if(hero.hitTestObject(platform) && keyboardDown[Keyboard.UP] && keyboardDown[Keyboard.RIGHT]){
movex = 20;
hero.x = hero.x + movex;
gravity =-50;
hero.y = hero.y + gravity;
}
}

Related

Undefined Property Error 1120 moving functions?

I'm very, VERY new at flash, and I've tried really hard to figure this out but it's not working. I keep getting the same error: "1120 Access of undefined property goGame" on line 96 and "1136 Incorrect number of arguments expected 1" on line 82.
I know both of these errors has something to do with the ordering of my functions, but I find that when I move the functions to be in front of the listener, more errors pop up demanding the same thing, and the only way I can fix those is moving them in front of each other etc. etc. So I'm kind of stuck. Help would be great appreciated!
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import fl.motion.MotionEvent;
import flash.utils.Timer;
import flash.utils.*;
public class StartGame extends MovieClip
{
var questions: Array=new Array();
var correctAnswers: Array=new Array("blue","Russia","10","stone","true","hydrogen and oxygen","Rapunzel","magician","The Mona Lisa","string","12","mammal","lightning bolt","lacrosse","do");
//Creates am array used for the Quiz Time function
var i = 0;
//used to track player's movements on board
var lives = 3;
//the # of lives given at the beginning of the game
var collide: Boolean;
var myTimer: Timer = new Timer(1000, 60);
//used for timer in Storming the Castle Game
var count = 0;
//used to manage chibiKing movements
//stage.addEventListener(Event.ENTER_FRAME,onFrameLoop);
//loops frames card so animation plays
//function to get to the master instructions page
//function to get the the main board
function randomNumber(){
var number=Math.round(Math.random()*5)+1;
return number;
}//end randomNumber function
function StartGame()
{
instructionsButton.addEventListener(MouseEvent.CLICK, masterInstructions);
//listener on instructions button to open the instructions page
goButton.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}//end StartGame function
function masterInstructions (event:MouseEvent) {
gotoAndPlay(2);
//takes you to the master instructions page
goButton2.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}// end masterInstructions function
function rollDie (event:MouseEvent) {
goRollButton.removeEventListener (MouseEvent.CLICK, rollDie);
//makes player unable to click roll button after pressing once
goRollButton.visible = false;
//removes visiblity of the roll button one clicked
goButtonGame.visible = true;
//makes game button appear so player can proceed to game
var currentRoll=randomNumber();
//randomly rolls a number between 1 and 6
outputNumber.text=String(currentRoll);
//displays the number rolled
var newMoves = i + currentRoll*10;
//moves player forward, i being the number already moved
//roll multipled by ten for frame movements of tween
gameboy.gotoAndStop(newMoves);
//player stops at the new position
i = newMoves;
//i now changed to rolled number
if (i<=300) {
bossGame();
}//if player gets to end of board, automatically start boss game
}//end rollDie function
function playGame (event: MouseEvent) {
gotoAndPlay(3);
//goes to main board game
livesOutput.text=String(lives);
//displays the 3 of lives the player has in the output box
gameBoard.addEventListener(MouseEvent.CLICK, girlJumps);
//event listener for a pop up
goRollButton.addEventListener(MouseEvent.CLICK, rollDie);
//when pressed, button calls die roll function
goButtonGame.addEventListener(MouseEvent.CLICK, goGame);
//when pressed, chooses a random mini game
ball.addEventListener(MouseEvent.MOUSE_DOWN,ballStartDrag);
ball.addEventListener(MouseEvent.MOUSE_UP, ballEndDrag);
bear.addEventListener(MouseEvent.MOUSE_DOWN, bearStartDrag);
bear.addEventListener(MouseEvent.MOUSE_UP, bearEndDrag);
//functions to create drag and drops for objects on stage game board
goButtonGame.visible=false;
//does not display go button so player must roll dice before playing game
}//end playGame function
function ballStartDrag (evt:MouseEvent) {
ball.startDrag();
}//end ballStartDrag function
function bearStartDrag (evt:MouseEvent) {
bear.startDrag();
}//end bearStartDrag function
function ballEndDrag (evt:MouseEvent) {
ball.stopDrag();
}//end ballEndDrag function
function bearEndDrag (evt:MouseEvent) {
bear.stopDrag();
}//end bearEndDrag function
function girlJumps (evt:MouseEvent) {
girlJump.gotoAndPlay(2);
//has character on board to appear by playing tween
}//end girlJumps function
function bossGame (event:KeyboardEvent) {
stage.addEventListener( KeyboardEvent.KEY_DOWN, finalBoss);
//listener to player movement when keyboard is pressed
addEventListener(Event.ENTER_FRAME,movefireball);
//listener to move the fireball
stage.addEventListener(Event.ENTER_FRAME, collision);
//listener to collisions between symbols on stage
livesBoss.text=String(lives);
//displays number of lives in text box
fireball.height = 100;
fireball.width = 100;
fireball.x=40
fireball.y=40
fireball.xVelocity=8;
fireball.yVelocity=8;
//sets fireball parameters
}//end bossGame function
function movefireball (evt: Event) {
fireball.x +=fireball.xVelocity;
fireball.y +=fireball.yVelocity;
//creates speeds of fireball
checkfireballtoWall();
//calls function
var move1:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
var move2:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
//movements randomly created for king's movements
if (count%100 == 0) {
chibiKing.x= move1;
chibiKing.y= move2;
//reassigns chibiKing's movements
}
count++;
//adds to count after so many seconds
}//end movefireball function
function checkfireballtoWall(){
const TOP: Number= 50;
const BOTTOM: Number= stage.stageHeight;
const LEFT: Number= 50;
const RIGHT: Number= stage.stageWidth - 50;
const REVERSE: int = -1;
//limits to fireball's movements
if (fireball.y<TOP) {
fireball.y=TOP;
fireball.yVelocity*=REVERSE;
}
else if (fireball.y>BOTTOM) {
fireball.y=BOTTOM;
fireball.yVelocity*=REVERSE;
}
if (fireball.x<LEFT) {
fireball.x=LEFT;
fireball.xVelocity*=REVERSE;
}
else if (fireball.x>RIGHT) {
fireball.x=RIGHT;
fireball.xVelocity*=REVERSE;
}
//reassignes fireball's direction if fireball hits a certain area
}//end checkfireballtoWall function
function finalBoss (evt: KeyboardEvent) {
if( evt.keyCode == Keyboard.LEFT )
{player.x = player.x - 6;
}
else if( evt.keyCode == Keyboard.UP )
{player.y = player.y - 6;
}
else if( evt.keyCode == Keyboard.RIGHT )
{player.x = player.x + 6;
}
else if( evt.keyCode == Keyboard.DOWN )
{player.y = player.y + 6;
}//allows player to move via keyboard control
}//end finalBoss function
function collision (evt: Event) {
if (player.hitTestObject(chibiKing)) {
gotoAndPlay(14);
//if player hits the king, automatically go to win game screen
if (player.hitTestObject(fireball)) {
lives = lives - 1;
//if player hits fireball, lose a life
if (lives == 0) {
gotoAndPlay(11);}
//if lives equal to zero, go automatically to lose game screen
livesBoss.text=String(lives);
//display the lives remaining the text box
}
}//end collision function
function dragonBattle (event:KeyboardEvent) {
//inset Dragon Battle code
}//end dragonBattle function
function goGame (event:MouseEvent) {
var gameChoose=randomNumber();
//randomly chooses a game to play from the existing mini games
if (gameChoose==1 || gameChoose == 2) {
gotoAndPlay(4);
//game 1 start screen
goButton3.addEventListener (MouseEvent.CLICK, stormingTheCastle);
//listener to go to Storming the Castle Game
}//end goGame function
else if (gameChoose==3 && correctAnswers.length>0) {
gotoAndPlay(7)
//quiz time start screen
quizTimeButton.addEventListener (MouseEvent.CLICK, quizTime);
//quiz time start
}
else {gotoAndPlay(6);
//game 2 start screen
goButton5.addEventListener (MouseEvent.CLICK, dragonBattle);
//listener to start game 2
//wizardess.addEventListener (MouseEvent.CLICK, wizardessMagic);}
}
}//end goGame function
function quizTime (event:MouseEvent) {
questions [0]= "What colour is the sky?";
questions [1]= "What is the world's biggest country in land mass?";
questions [2]= "Do Re Mi Fa So La Ti...";
questions [3]= "How many tentacles does a squid have?";
questions [4]= "In Greek Mythology, looking into Medusa's eyes would turn you to...?";
questions [5]= "True or False: Winnipeg has a hockey team.";
questions [6]= "Water is made out of...?";
questions [7]= "Which princess is the star of Disney's movie 'Tangled'?";
questions [8]= "Harry Houdini was famous for being a(n)...?";
questions [9]= "Leonardo Da Vinci famously painted what?";
questions [10]= "What type of instrument is a sitar?";
questions [11]= "How many are in a dozen?";
questions [12]= "Humans are...?";
questions [13]= "Harry Potter is famous for having a scar shaped as what on his forehead?";
questions [14]= "What is the national sport of Canada?";
//creates questions to go with answers created in startGame function
questionBox.text=questions[questions.length];
//displays the question at the end of the array
answerQuizTime.addEventListener(MouseEvent.CLICK, quiz);
//button to proceed to get quiz marker
}//end quizTime function
function quiz (evt:MouseEvent){
var userAnswer=String(answerInput.text);
//saves the user's answer in userAnswer variable
if (userAnswer==correctAnswers[questions.length]) {
questions.pop();
//removes question from end of array
lives = lives + 1;
//adds life to player's total lives
gotoAndPlay(9);
//goes to minigame win screen
}
else {
questions.pop();
//removes question from end of array
lives = lives - 1;
//removes life from player's total lives
gotoAndPlay(10);
//goes to minigame lose screen
}
}//end quiz function
// handler function for the Arrow Keys to move Player across the stage
function movePlayer(evt: KeyboardEvent) {
// if key is right arrow, move Player to the right
if (evt.keyCode == Keyboard.RIGHT) {
Player.x += 20;
// if key is left arrow, move Player to the left
} else if (evt.keyCode == Keyboard.LEFT) {
Player.x -= 20;
}
}//end movePlayer function
function stormingTheCastle (event:MouseEvent) {
// add a listener for a Frame Event
stage.addEventListener(Event.ENTER_FRAME, onFrameLoop);
// add the listener for Keyboard events to the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, movePlayer);
// create a custom speed property for each knight
//start timer
knight1.velocity = 4;
knight2.velocity = 6;
knight3.velocity = 3;
knight4.velocity = 5;
collide = false;
myTimer.start();
}//end stormingTheCastle function
// each time frame 1 plays, move each knight
//continues if no collision and count less than 60
//return each night to top if it reaches the bottom
function onFrameLoop(evt: Event) {
if (collide == false && myTimer.currentCount < 60) {
if (knight1.y > 292.2)
{knight1.y = 42.45;}
if (knight2.y > 292.2)
{knight2.y = 42.45;}
if (knight3.y > 292.2)
{knight3.y = 42.45;}
if (knight4.y > 292.2)
{knight4.y = 42.45;}
//move knights down by its speed property amount
knight1.y = knight1.y + knight1.velocity;
knight2.y = knight2.y + knight2.velocity;
knight3.y = knight3.y + knight3.velocity;
knight4.y = knight4.y + knight4.velocity;
//trace timer count
trace(myTimer.currentCount);
//if Player is hit by a knight collision is true
if (knight1.hitTestObject(Player) == true) {
collide = true;
trace("test");
}
if (knight2.hitTestObject(Player) == true) {
collide = true;
}
if (knight3.hitTestObject(Player) == true) {
collide = true;
}
if (knight4.hitTestObject(Player) == true) {
collide = true;
}
else {
if (lives == 0) {
gotoAndPlay(11);}
//trace Game Over when collision is true
trace("GAME OVER");
gotoAndPlay(10);
}
} //end onFrameLoop function
}
}//end startGame function
}//end class function
}//end package
In a class file, the order of functions and var definitions is not an issue (aside from anonymous and nested functions which you should probably steer clear of anyway).
Let's start with line 82. You call bossGame(), but when you look at the function, you've defined it so it requires a parameter:
function bossGame (event:KeyboardEvent)
It's expecting you to pass a KeyboardEvent to the function. Though I'm not sure why because looking at that function it seems to have nothing to do with Keyboard input nor does it use that event in any way.
So, take out the parameter:
function bossGame()
Or, make it optional by giving it a default value:
function bossGame(event:KeyboardEvent = null)
For the second error. Your goGame function is actually nested inside another function collision() , so it has no scope except inside the collision function. If you want to be able to access it outside of that function, then you should break it out.
As an aside, you comments beside your closing function brackets are often incorrect making it difficult to read your code.

Why doesn't my KEY_DOWN event fire?

I am new to ActionScript and was following the tutorial here to get me started using FlashDevelop. I set it up to move the item every KEY_DOWN event instead of using the frame event but my KEY_DOWN event is never fired. I quickly added a MOUSE_DOWN event to test the extent of the problem which works.
I am adding the listeners as my Paddle (an extension of Sprite) item is added to the stage:
private function addedToStage(e:Event) : void {
// Remove this event listener
removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
// Add the picture
addChild(pic);
// Set the location of the item in the middle of the screen one
// height length of the image down.
this.y = this.height;
this.x = (this.stage.stageWidth - this.width) / 2;
// Add the keyboard listener (broken).
stage.addEventListener(KeyboardEvent.KEY_DOWN, this.keyDownHandler, false, 0, true);
// Add the mouse listener (works).
stage.addEventListener(MouseEvent.MOUSE_DOWN, this.mouseDown, false, 0, true);
// Set the focus to the stage.
stage.focus = stage;
}
I have a breakpoint in my keyDownHandler function and it is never called.
This may be a duplicate of this question, but I am already doing what the answer in that question describes and in the comments he explains that he does not know what fixed the problem only that it suddenly started working.
Another popular answer to that question mentions this article which is why there is a line in my code to set the focus back to the stage. There is nothing else on my stage.
What could be happening?
Edit:
Here is my listener code:
private function keyDownHandler(e:KeyboardEvent):void {
var increment:Number; // Here is my breakpoint
if (e.keyCode == 65 || e.keyCode == 37) {
increment = -5;
} else if(e.keyCode == 68 || e.keyCode == 39) {
increment = 5;
}
var newX:Number = this.x + 5;
if (newX > 0 && newX + this.width < this.stage.width) {
this.x = newX;
}
}
The problem was unrelated to the event itself, but rather how I was testing to see if it fired. You cannot place breakpoints on declarations.
FlashDevelop will allow you to set a breakpoint there but the debugger will not actually stop at this point.
The code to move the paddle does not work (not surprising to me at this point), but if I move the breakpoint to the line in the if statement (or any other line when an actual action performed such as the trace) suddenly it breaks fine. Now that I think about it even the other languages I've worked with have this behavior, I'm just too pampered by IDE's that will move the breakpoint to the nearest available line in such situations.

as3 continuous movement of object with touch event

i am attempting to make an interactive scene fot my nexus 7 using actionscript. i am attempting to make a nape body to move continuously while a button is being pressed. the trace(event.target.name); in the tap handler is returning the instance name of the button being pressed as i expected it to but the same trace statement in the enter_frame pressed function is returning the buttons parent name and thus the movement is not happening below is my code..
resetBtn.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler);
ballBtn.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
private function tapHandler(event:TouchEvent):void
{
//listen for mouse up on the stage, in case the finger moved off of the button accidentally when they release.
rightArrow.addEventListener(TouchEvent.TOUCH_END, endTouch);
//while the mouse is down, run the tick function once every frame as per the project frame rate
addEventListener(Event.ENTER_FRAME, pressed);
trace(event.target.name);
//ball.applyImpulse(new Vec2(25,0));
}
function endTouch(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, pressed);
//stop running the tick function every frame now that the mouse is up
this.removeEventListener(TouchEvent.TOUCH_END,endTouch);
//remove the listener for endTouch
}
function pressed(e:Event):void
{
space.step(1 / stage.frameRate);
trace(e.target.name);
if(e.target.name == "leftArrow")
{
trace("going left");
crane.position.x -= 5;
boom.position.x -= 5;
c.position.x -= 5;
}
if(e.target.name == "rightArrow")
{
trace("going Right");
crane.position.x += 5;
boom.position.x += 5;
c.position.x += 5;
}
}
if you can help me fix this or suggest a better way of achieving this wour help would be greatly appreciated.
Your issue is basically that you're adding the listener to the parent for the Enter_frame events so the target when that event dispatches isn't your buttons as you desire. I think instead of moving the listener though you're better off using a variable to hold a reference to your buttons like this:
private var curButton:Sprite;
resetBtn.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler);
ballBtn.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN , tapHandler );
private function tapHandler(event:TouchEvent):void
{
curButton = event.target;
curButton.addEventListener(TouchEvent.TOUCH_END, endTouch);
addEventListener(Event.ENTER_FRAME, pressed);
}
function endTouch(e:Event):void
{
trace("touch end received");
removeEventListener(Event.ENTER_FRAME, pressed);
curButton.removeEventListener(TouchEvent.TOUCH_END, endTouch);
curButton = null;
}
function pressed(e:Event):void
{
trace("currently pressed");
space.step(1 / stage.frameRate);
if(curButton == leftArrow)
{
trace("going left");
crane.position.x -= 5;
boom.position.x -= 5;
c.position.x -= 5;
}
if(curButton == rightArrow)
{
trace("going Right");
crane.position.x += 5;
boom.position.x += 5;
c.position.x += 5;
}
}
Okay see my edits above, hopefully should help resolve. Also as it seems you've probably already figured out the instance name that you give a variable when you define it, isn't the same as the .name property or the .id property, the instance name is no longer available at run time (if you really want to you can use the name property but you have to populate it yourself, and generally it's best to just use the instance names in the code instead, as this is checked at compile time, and incurs no extra run-time overhead).

Creating collision detection on more than one variable in a for loop?

Essentially I am trying to create a game, where the player has to dodge certain items, so far I have a piece of code that randomly adds 3 sharks to the stage.
The idea is that once the player has hit a shark he/she returns to the start location, I have an Action Script file that contains the speed,velocity etc of the shark, the every time the program is run the sharks will appear in a different location.
However, when I attempt to do a collision test of the sharks only one of the sharks respond, I cannot figure out how to make it that all 3 sharks effect the player (square_mc). Any help would be greatly appreciated.
//Pirate game, where you have to avoid particular object and get to the finish line to move onto the final level.
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveMode );
function moveMode(e:KeyboardEvent):void {
//movements for the pirate ship, this will allow the ship to move up,down,left and right.
if (e.keyCode == Keyboard.RIGHT) {
trace("right");
square_mc.x = square_mc.x + 25;
}
else if (e.keyCode == Keyboard.LEFT) {
trace("left");
square_mc.x = square_mc.x - 25;
}
else if (e.keyCode == Keyboard.UP) {
trace("up");
square_mc.y = square_mc.y - 25;
}
else if (e.keyCode == Keyboard.DOWN) {
trace("down");
square_mc.y = square_mc.y + 25;
}
}
//for.fla
//this program uses a for loop to create my Sharks
//a second for loop displays the property values of the sharks
function DisplayShark():void{
for (var i:Number=0;i<3;i++)
{
var shark:Shark = new Shark(500);
addChild(shark);
shark.name=("shark"+i);
shark.x=450*Math.random();
shark.y=350*Math.random();
}
}
DisplayShark();
for(var i=0; i<3;i++){
var currentShark:DisplayObject=getChildByName("shark"+i);
trace(currentShark.name+"has an x position of"+currentShark.x+"and a y position of"+currentShark.y);
}
//here we will look for colliosion detection between the two move clips.
addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void {
if (square_mc.hitTestObject(currentShark))
{
trace("The Square has hit the circle");
square_mc.x=50
square_mc.y=50 //these lines of code return the square back to it's original location
}
}
Just move your for loop into the ENTER_FRAME:
addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void {
for(var i=0; i<3;i++){
var currentShark:DisplayObject=getChildByName("shark"+i);
if (square_mc.hitTestObject(currentShark))
{
trace("The Square has hit the circle");
square_mc.x=50;
square_mc.y=50;
}
}
}
You can't just go through the for loop once and set the currentShark variable - you'll just end up testing against one shark every time you perform the collision test. Rather, every time you want to check collisions you must loop through all the sharks and do the collision testing.

In Flash Actionscript 3.0 how do I create smooth keyboard controls for player movement?

I am a beginner in Flash Actionscript 3.0 programming. I am trying to create smooth keyboard controls for player movement in a game.
I'm currently using addEventListener(KeyboardEvent.KEY_DOWN) listening for a keyboard key press and then within the handler function moving a graphic by adding a number to its .x or .y property.
This creates a slow, sluggish jerk at the beginning. I know there's a smoother, more responsive way to do this but have no idea where to begin. Any help would be appreciated!
For smooth keys I would suggest using either a Timer or onEnterFrame to poll for keys often enough to get smooth controls. It will get the job done, but at a certain expense. If you've got the rest of the logic all fine, this should fit in ok:
var key:int = NaN;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyRelease,false,0,true);
this.addEventListener(Event.ENTER_FRAME,update,false,0,true);
function onKeyPress(event:KeyboardEvent):void {
key = event.keyCode;
event.stopPropagation();
}
function onKeyRelease(event:KeyboardEvent):void {
key = NaN;
event.stopPropagation();
}
function update(event:Event):void{
if(key) trace(key);
}
I make sure the event doesn't bubble by stopping it's propagation, and it's set on the stage which should be the topmost level, event wise. Also I'm using the key only the key is down, otherwise I ignore it in the enterFrame handler.
HTH,
George
Where are you placing the listener? Is it in the application, or in the sprite that is supposed to move? Does the sprite have the focus when you are pressing the key?
Also, in adding the event listener, are you using capture? That is, are you setting the 3rd argument to true, as in
addEventListener(KeyboardEvent.KEY_DOWN, yourHandler, true)
If you use capture, which is how you have to do it if the App itself is listening for the event, then you will get a certain amount of latency, and this latency will be greater the more complex the interface is. If those events have to work their way up a vast hierarchy, this could be noticeable. If there are many sprites, this can exacerbate the problem.
What you can do is have the sprite that has the focus dispatch a custom event which a controller class listens to for each sprite. The controller class will have a handler that moves the event.currentTarget however you plan to have it done.
Also read up about custom events and how to use the SystemManager to add and remove listeners dynamically: http://livedocs.adobe.com/flex/3/langref/index.html.
the most simplest example to this would be this.
here you have a controllable Ship class(Ship.as).
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
public class Ship extends MovieClip {
private var speedX;
private var speedY;
public function Ship() {
//constructor
stage.addEventListener(KeyboardEvent.KEY_DOWN ,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP ,keyUp);
stage.addEventListener(Event.ENTER_FRAME, update);
}
public function keyDown(e:KeyboardEvent) {
if(e.keyCode == 37) {
speedX = -5;
}
if(e.keyCode == 38) {
speedY = -5;
}
if(e.keyCode == 39) {
speedX = 5;
}
if(e.keyCode == 40) {
speedY = 5;
}
}
public function keyUp(e:KeyboardEvent) {
if(e.keyCode == 37 || e.keyCode == 39) {
speedX = 0;
}
if(e.keyCode == 38 || e.keyCode == 40) {
speedY = 0;
}
}
public function update(e:Event) {
x += speedX;
y += speedY;
}
}