AS3 MouseEvents - actionscript-3

I'm doing a top-down view game. Is a really simple one in fact. The character moves when the player click in the screen. But, I have a fire button too.
I want know how I can disable the mouse from click when player press the button. Because when this happen the character moves to button spot.
Here's my code:
var walk = false;
var goX = player.x;
var goY = player.y;
var speed = 10;
var dir = "down";
stage.addEventListener(Event.ENTER_FRAME, loop);
btn.addEventListener(MouseEvent.MOUSE_DOWN, btn1);
function btn1(event:MouseEvent):void
{
fireBullet();
}
function fireBullet():void {
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
if(char.scaleY < 0){
playerDirection = "up";
} else if(char.scaleY > 0){
playerDirection = "down";
}
var bullet:Bullet = new Bullet(player.x, player.y, playerDirection);
stage.addChild(bullet);
}
function loop(Event)
{
if (walk == true)
{
player.w.play();
}
else
{
player.w.gotoAndStop(1);
}
player.gotoAndStop(dir);
if ((goY-speed)>player.y)
{
player.y += speed;
dir = "down";
}
else if ((goY+speed)<player.y)
{
player.y -= speed;
dir = "up";
}
if ((goX-speed)>player.x)
{
player.x += speed;
dir = "right";
}
else if ((goX+speed)<player.x)
{
player.x -= speed;
dir = "left";
}
if ((goY-speed)>player.y || (goY+speed)<player.y || (goX-speed)>player.x || (goX+speed) <player.x){
walk = true;
} else {
walk =false
}
}
stage.addEventListener(MouseEvent.CLICK, set);
function set(MouseEvent){
goX=mouseX
goY=mouseY}
Thanks.

Since mouse events bubble up the display list and you have a listener added to the stage, when the user presses a button, you need to stop the event from propagating.
In order to achieve this, in the button handler, you would need to the call stopImmediatPropagation method. So, your btn1 method would look like this:
function btn1(event:MouseEvent):void
{
fireBullet();
event.stopImmediatePropagation();
}
This way, you prevent the click event from bubbling all the way up to the stage, in turn causing the stage's click handler to be called.
Hope this helps. Have a great day.

simply, using the concept of target can be handled as follows.
try this:
function set(e:MouseEvent):void
{
var target = e.target;
//ex) if(target is MovieClip) return;
if(target is <#your fire button type#>) return;
goX=mouseX;
goY=mouseY;
}
what is different "target" vs "currentTarget"?
target: the object that fired event.
currentTarget: the object that you applied the listener to.

Related

Speed keeps stacking in actionscript 3.0

We have been making this game for our class CPT and you play as a character and try to get through these levels but the issue is that every time you die and go back to play the level again the speed stacks on top of the previous speed to a point where the game isn't even playable anymore. We have tried resetting it and setting it back to 0 but nothing seems to work we also tried to code it so that is the speed goes past 21 it resets back to 20 (our ideal speed) we also tried to remove extra event listeners that could have been stacking on top of the other. and if you do happen to die but get to the next frame the speed goes back to 20 for that frame.But if you die on that frame it doubles the speed on that frame too.Our code is:
import flash.events.Event;
import flash.display.MovieClip;
//makes the character jump
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, whenKeyPressed);
stage.addEventListener(Event.ENTER_FRAME, update);
function whenKeyPressed(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(event:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
//when the character makes it to the other side of the screen, the frame
changes
if (player_mc.hitTestObject(frameChanger1))
{
gotoAndStop(91);
}
//end the game when the character touches the penguin
if (player_mc.hitTestObject(penguin1))
{
gotoAndStop(89);
}
}
//makes the character move left and right
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
player_mc.addEventListener(Event.ENTER_FRAME, moveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, setKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, unsetKeyPressed);
function moveInDirectionOfKey(event:Event)
{
if (leftPressed)
{
player_mc.x -= 20;
}
if (rightPressed)
{
player_mc.x += 20;
}
}
function setKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function unsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
//when the character makes it to the other side of the screen, the frame
changes
if (player_mc.hitTestObject(frameChanger1))
{
gotoAndStop(91);
}
//end the game when the character touches the penguin
if (player_mc.hitTestObject(penguin1))
{
gotoAndStop(89);
}
}
Did You tried :
if(!stage.hasEventListener(Event.ENTER_FRAME)){
stage.addEventListener(Event.ENTER_FRAME, update);
}
if(!stage.hasEventListener(KeyboardEvent.KEY_DOWN)){
stage.addEventListener(KeyboardEvent.KEY_DOWN, setKeyPressed);
}
if(!stage.hasEventListener(KeyboardEvent.KEY_UP)){
stage.addEventListener(KeyboardEvent.KEY_UP, unsetKeyPressed);
}
if(!player_mc.hasEventListener(Event.ENTER_FRAME)){
player_mc.addEventListener(Event.ENTER_FRAME, moveInDirectionOfKey);
}
And so on...
Otherwise You will register the Events multiple times...
This may be the issue.
I'm not sure, I avoid to code on multiple frames.
You may also use the answer of #Philarmon here Function being called faster

My Character Won't Move :( Multiple .as files AS3

I have a few .as files. They are: MainClass.as, FrontEnd.as, Levels.as, and Hero.as. My problem (as far as I know) is in my Hero.as file. Let me descibe how I have it all set up thusfar because I have been a bit concerned that there are better ways of doing things in AS3.
MainClass.as makes a variable of FrontEnd (menus, namely the main menu) and calls it up (addChild).
FrontEnd.as are my menus. buttons and whatnot...
Levels.as right now just calls up level 1 when the start new game button is pressed on the main menu. Had one hell of a time figuring out how to use functions from a different .as file. Hero.as I will add my code for. I'm posting the whole thing because I don't know where my problem is.
public class Hero extends MovieClip
{
public var roger:player = new player();
private var animationState:String = "down";
public var facing:String = "down";
private var isLeft:Boolean = false;
private var isRight:Boolean = false;
private var isUp:Boolean = false;
private var isDown:Boolean = false;
public var currentPlayer:MovieClip = roger;
public function Hero()
{
addEventListener(Event.ENTER_FRAME, loop);
addEventListener(Event.ADDED_TO_STAGE, onStage);
trace(currentPlayer);
}
public function onStage( event:Event ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onStage );
}
public function addCurrentPlayer():void
{
roger.x = stage.stageWidth * .5;
roger.y = stage.stageHeight * .5;
addChild(roger);
currentPlayer = roger;
setBoundaries();
}
public function keyDownHandler(event:KeyboardEvent)
{
if (event.keyCode == 39)//right press
{
isRight = true;
}
if (event.keyCode == 37)//left pressed
{
isLeft = true;
}
if (event.keyCode == 38)//up pressed
{
isUp = true;
}
if (event.keyCode == 40)//down pressed
{
isDown = true;
}
}
public function keyUpHandler(event:KeyboardEvent)
{
if (event.keyCode == 39)//right released
{
isRight = false;
}
if (event.keyCode == 37)//left released
{
isLeft = false;
}
if (event.keyCode == 38)//up released
{
isUp = false;
}
if (event.keyCode == 40)//down released
{
isDown = false;
}
}
public function loop(Event):void
{
if (currentPlayer == null)
{
addCurrentPlayer();//make sure at least roger is on the screen
}
currentPlayer.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
currentPlayer.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
//----------------------------------0
//Animation States
//----------------------------------0
if (isDown == true)
{
currentPlayer.y += 5;
animationState = "walk_down";
facing = "down";
currentPlayer.gotoAndStop(animationState);
}
else if (isUp == true)
{
currentPlayer.y -= 5;
animationState = "walk_up";
facing = "up";
currentPlayer.gotoAndStop(animationState);
}
else if (isRight == true)
{
currentPlayer.x += 5;
animationState = "walk_right";
facing = "right";
currentPlayer.gotoAndStop(animationState);
}
else if (isLeft == true)
{
currentPlayer.x -= 5;
animationState = "walk_left";
facing = "left";
currentPlayer.gotoAndStop(animationState);
}
//----------------------------------0;
//IDLE STATES
//----------------------------------0
else if (isDown == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isUp == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isRight == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isLeft == false)
{
currentPlayer.gotoAndStop(facing);
}
}
public function setBoundaries():void
{
var halfHeight:int = currentPlayer.height * .5;
var halfWidth:int = currentPlayer.width * .5;
if(currentPlayer.y <= 1)
{
currentPlayer.y += halfHeight;
}
else if(currentPlayer.y > stage.stageHeight)
{
currentPlayer.y -= halfHeight;
}
else if(currentPlayer.x <= 1)
{
currentPlayer.x += halfWidth;
}
else if(currentPlayer.x > stage.stageWidth)
{
currentPlayer.x -= halfWidth;
}
}
}
}
trace(currentPlayer); is giving me [object player] instead of the instance name "roger". (Later on I want more playable characters.) I'm not sure if the problem is there or in my levels file, which I'll post here. (not as long as Hero.as)
public class Levels extends MovieClip
{
var currentLevel:MovieClip;
public function Levels()
{
addEventListener(Event.ADDED_TO_STAGE, onStage);
}
private function onStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
}
public function gotoLevelOne():void
{
var levelOne:LevelOne = new LevelOne();
var hero:Hero = new Hero();
addChild(hero);
levelOne.x = stage.stageWidth * .5;
levelOne.y = stage.stageHeight * .5;
addChild(levelOne);
currentLevel = levelOne;
hero.currentPlayer.x = 100;
hero.currentPlayer.y = 100;
addChild(hero.currentPlayer);
}
}
}
If I remove = roger; from var currentPlayer:MovieClip = roger; it gives me #1009 null object even though I told it in addCurrentPlayer() to change currentPlayer to roger. On level 1, everything shows up but I can't move my character. I know that it worked when I was working on his animations and I would call him to the main menu. Everything worked on him. What's the problem now?
Firstly, there's a lot of things wrong with your code:
In your Hero Class, the 'onStage' Event handler doesn't actually do anything other than remove the event listener that triggers it. While it's good practice to remove the event listener, there should be some other purpose to the Event handler. If there isn't you can remove it and not bother listening for the ADDED_TO_STAGE Event.
Similarly, in your Levels Class 'onStage' Event handler you attempt to remove the event, but name the wrong handler. I assume you want to remove the event handler and then run the 'gotoLevelOne' method. If so, just have the Event.ADDED_TO_STAGE listener call 'gotoLevelOne' and then remove the Event listener there:
public function Levels()
{
addEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
}
public function gotoLevelOne():void
{
removeEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
// class continues....
OK, so to your question:
You will be getting the null error because you are referring to currentPlayer from outside the Hero Class, before calling addCurrentPlayer (where it is set).
If you temporarily define currentPlayer as a private variable, the compiler should give you a line number where you first refer to currentPlayer from OUTSIDE the Hero Class (the error will be something like 'Class X is trying to access a private (or non-existent) property of Y Class').
You can then sort out WHY you are accessing currentPlayer before calling addCurrentPlayer. You may also want to think about if currentPlayer NEEDS to be public (if so, then what is 'addCurrentPlayer' for? That function effectively works as a setter for currentPlayer).
EDIT:
At the moment you are adding new KEY_DOWN and KEY_UP event listeners EVERY frame of your game loop. This is unnecessary. Add them both ONCE in the initialisation of your game (perhaps in your Hero's onStage handler), and count on them to trigger the appropriate handlers.
You will want to add the KEY_DOWN and KEY_UP listeners to 'stage', not currentPlayer, so:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
You will need to add the listeners AFTER your Hero instance has been added to the Stage though, so it has access to 'stage'. That's why it makes sense to add the listeners in the Hero's onstage handler.

Making an object or layer transparent when another object passes over it. (Flash Actionscript 3.0)

I'm very new to coding and am having trouble finishing the last little bit of a mini game type project for school.
So this is a draft of what the program looks like so far: http://aaronmillard.com/dir/wp-content/uploads/2013/08/Google-Doodle_Roomba.swf
Now what I want the program to do is "vacuum" up the google when the roomba drives over it. The easiest way to achieve this (I think) is to have an exact replica of the carpet layer without the google logo beneath the carpet layer with the google logo. So I would need to code something like "when the object(roomba) passes over object(carpetwithgooglelogo) make object(carpetwithgooglelogo) have 0 opacity." I just can't figure out how to say that in code.
The code as of right now look like this:
// Assign 4 booleans for the 4 arrow keys
var keyUp = false;
var keyDown = false;
var keyLeft = false;
var keyRight = false;
// Add the keyboard event (KEY_DOWN) on the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
function pressKey(pEvent)
{
// If an arrow key is down, switch the value to true to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = true;
}
else if (pEvent.keyCode == 40)
{
keyDown = true;
}
else if (pEvent.keyCode == 37)
{
keyLeft = true;
}
else if (pEvent.keyCode == 39)
{
keyRight = true;
}
}
// Add the keyboard event (KEY_UP) on the stage
stage.addEventListener(KeyboardEvent.KEY_UP, releaseKey);
function releaseKey(pEvent)
{
// If the arrow key is up, switch the value to false to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = false;
}
else if (pEvent.keyCode == 40)
{
keyDown = false;
}
else if (pEvent.keyCode == 37)
{
keyLeft = false;
}
else if (pEvent.keyCode == 39)
{
keyRight = false;
}
}
// Set the velocity of the object
var speed = 4;
// And the rotation speed
var rotationSpeed = 6;
// Add an enter frame event on the moving object
myCircle.addEventListener(Event.ENTER_FRAME, circleEnterFrame);
function circleEnterFrame(pEvent)
{
// Set the default velocity to 0 if no key is pressed
var velocity = 0;
if (keyUp)
{
// If the key up is pressed set the new velocity to the speed value
velocity = speed;
}
if (keyDown)
{
// If the key down is pressed set the new velocity to the half speed value
velocity = -speed/2;
}
if (keyLeft)
{
// rotate the object
pEvent.currentTarget.rotation -= rotationSpeed;
}
if (keyRight)
{
// rotate the object
pEvent.currentTarget.rotation += rotationSpeed;
}
// Convert the degreeAngle to the radian angle
var angleRadian = pEvent.currentTarget.rotation / 180 * Math.PI;
// Move the object with the radian angle and the object speed
pEvent.currentTarget.x += Math.cos(angleRadian) * velocity;
pEvent.currentTarget.y += Math.sin(angleRadian) * velocity;
}
Any help would be very much appreciated! Thanks!
The easiest way is to do something like this:
if( roomba.hitTestObject(google)){
google.alpha = 0;
}
You'll have to check this on every frame using an ENTER_FRAME event.
If this is confusing tell me in the comments and I will clarify with more code.

random enemies in vertical shooter AS3

I have a vertical shooter game I'm working on. I need to find a way to make random objects(enemies) drop down from the top. At the moment I've got 1 enemy that drops down randomly from the top which is working. here is the code I'm using.
Main code
// Full Screen Command
fscommand("fullscreen","true");
stop();
//center player on screen
mcMain.x = 880,45;
mcMain.y = 940,40;
//these booleans will check which keys are down
var leftDown:Boolean = false;
var upDown:Boolean = false;
var rightDown:Boolean = false;
var downDown:Boolean = false;
//how fast the character will be able to go
var mainSpeed:int = 25;
//how much time before allowed to shoot again
var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
var cLimit:int = 12;
//whether or not the user is allowed to shoot
var shootAllow:Boolean = true;
//how much time before another enemy is made
var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
var enemyLimit:int = 16;
//the player's score
var score:int = 0;
//this movieclip will hold all of the bullets
var bulletContainer:MovieClip = new MovieClip();
addChild(bulletContainer);
//whether or not the game is over
var gameOver:Boolean = false;
//adding a listener to mcMain that will move the character
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
//checking if the key booleans are true then moving
//the character based on the keys
if(leftDown){
mcMain.x -= mainSpeed;
}
if(upDown){
mcMain.y -= mainSpeed;
}
if(rightDown){
mcMain.x += mainSpeed;
}
if(downDown){
mcMain.y += mainSpeed;
}
//keeping the main character within bounds
if(mcMain.x <= 0){
mcMain.x += mainSpeed;
}
if(mcMain.y <= 0){
mcMain.y += mainSpeed;
}
if(mcMain.x >= stage.stageWidth - mcMain.width){
mcMain.x -= mainSpeed;
}
if(mcMain.y >= stage.stageHeight - mcMain.height){
mcMain.y -= mainSpeed;
}
//Incrementing the cTime
//checking if cTime has reached the limit yet
if(cTime < cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 0;
}
//adding enemies to stage
if(enemyTime < enemyLimit){
//if time hasn't reached the limit, then just increment
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
var newEnemy = new Enemy();
//making the enemy offstage when it is created
newEnemy.y = -1 * newEnemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newEnemy.x = int(Math.random()*(stage.stageWidth - newEnemy.width));
//then add the enemy to stage
addChild(newEnemy);
//and reset the enemyTime
enemyTime = 0;
}
//updating the score text
txtScore.text = 'SCORE: '+score;
}
//this listener will listen for down keystrokes
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void{
//making the booleans true based on the keycode
//WASD Keys or arrow keys
if(event.keyCode == 37 || event.keyCode == 65){
leftDown = true;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightDown = true;
}
//checking if the space bar is pressed and shooting is allowed
if(event.keyCode == 32 && shootAllow){
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = mcMain.x + mcMain.width/2 - newBullet.width/2;
newBullet.y = mcMain.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
mcMain.gotoAndPlay(1);
}
}
//this listener will listen for keys being released
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void{
//making the booleans false based on the keycode
if(event.keyCode == 37 || event.keyCode == 65){
leftDown = false;
}
if(event.keyCode == 39 || event.keyCode == 68){
rightDown = false;
}
}
enemy class
package{
//we have to import certain display objects and events
import flash.display.MovieClip;
import flash.events.*;
//this just means that Enemy will act like a MovieClip
public class Enemy extends MovieClip{
//VARIABLES
//this will act as the root of the document
//so we can easily reference it within the class
private var _root:Object;
//how quickly the enemy will move
private var speed:int = 5;
//this function will run every time the Bullet is added
//to the stage
public function Enemy(){
//adding events to this class
//functions that will run only when the MC is added
addEventListener(Event.ADDED, beginClass);
//functions that will run on enter frame
addEventListener(Event.ENTER_FRAME, eFrame);
}
private function beginClass(event:Event):void{
_root = MovieClip(root);
}
private function eFrame(event:Event):void{
//moving the bullet up screen
y += speed;
//making the bullet be removed if it goes off stage
if(this.y > stage.stageHeight){
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
//checking if it is touching any bullets
//we will have to run a for loop because there will be multiple bullets
for(var i:int = 0;i<_root.bulletContainer.numChildren;i++){
//numChildren is just the amount of movieclips within
//the bulletContainer.
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:MovieClip = _root.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget)){
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
//also remove the bullet and its listeners
_root.bulletContainer.removeChild(bulletTarget);
bulletTarget.removeListeners();
//up the score
_root.score += 5;
}
}
//hit testing with the user
if(hitTestObject(_root.deadLine)){
//losing the game
_root.gameOver = true;
_root.gotoAndStop('lose');
}
//checking if game is over
if(_root.gameOver){
removeEventListener(Event.ENTER_FRAME, eFrame);
this.parent.removeChild(this);
}
}
}
}
I'm using the tutorial from here : http://www.flashgametuts.com/tutorials/as3/how-to-make-a-vertical-shooter-in-as3-part-1/
any help is much appriciated.
I used to make games in flash and I used this condition to constantly add Enemies in my game.
if (Math.floor(Math.random() * 90) == 5){
under this condition you can use your code do add 1 enemy randomly
I think you shold get a timer class conected to your main code.
get a global counter.
int count=0;
int timeElapsedToNewEnemy = int((Math.random()*10+1)*10);
//get u a number from 10 to 100
get ur timer
var time:Timer=new Timer(100,0);// each 1/10 seconds
time.start();
time.addEventListener(TimerEvent.TIMER, countTime);
get ur function for timer
function countTime(e:TimerEvent):void
{//increment ur timer
count++;
if (cont == timeElapsedToNewEnemy)
{
cont=0;//restar ur counter..
//createUrNewEnemyHere
//get a new timeElapsedToEnemy
timeElapsedToNewEnemy = int((Math.random()*10+1)*10);
}
}
now u can easily adjust it to create random enemys each random x time.
let me know if its work for u
Thanks guys, but i found a solution.
var newEnemy = new (getDefinitionByName("Enemy"+Math.floor(Math.random()*4)));
and then created different movieclips of the enemy as enemy

How to do you get an character to jump?

This is my fist time ever needing to use this for one of my games. I want to have the character jump. I have been trying to get this result for about an hour, but with no luck =( I am using AS3, and flash CS5.5. So far all my code does is make the character go left, and right based on keyboard input. Could someone please help?
Here is my code so far:
public class Dodgeball extends MovieClip
{
public var character:Character;
public var rightDown:Boolean = false;
public var leftDown:Boolean = false;
public var speed:Number = 3;
public var timer:Timer;
public function Dodgeball()
{
character= new Character();
addChild(character);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, MyKeyUp);
timer = new Timer(24);
timer.addEventListener(TimerEvent.TIMER, moveClip);
timer.start();
}
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.RIGHT)
{
rightDown = true;
if(character.currentLabel != "walkingRight")
{
character.gotoAndStop ("walkingRight");
}
}
if (event.keyCode == Keyboard.LEFT)
{
leftDown = true;
if (character.currentLabel != "backingUp")
{
character.gotoAndStop("backingUp");
}
}
}
public function MyKeyUp(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
character.gotoAndStop("standing");
rightDown = false;
}
if (event.keyCode == Keyboard.LEFT)
{
character.gotoAndStop("standingLeft");
leftDown = false;
}
}
public function moveClip(event:TimerEvent):void
{
if (rightDown)
{
character.x += speed;
}
if (leftDown)
{
character.x -=speed;
}
event.updateAfterEvent();
}
}
}
One method you can try is found here: http://www.actionscript.org/forums/showthread.php3?t=256009 Like your speed variable, grav determines the vertical position of the character.
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onKeyDown(evt:KeyboardEvent):void
{
if(evt.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(evt:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
}
Edit: Jason's method is fine, but I'm not sure if it would be useful if you plan to have some kind of collision detection.
What I would do is create a motion tween of the character jumping. then call gotoAndPlay on that frame, and on the last frame of the tween put a stop, or a gotoAndStop on the "stationary" frame, or whatever frame represents a neutral position.
if (event.keyCode == Keyboard.SHIFT)
{
character.gotoAndPlay("simpleJump");
jumpDown = false;
}
This will give you the greatest animation control over the look and feel. You could also do it programmatically, but personally, I recommend against it. It will take less time to set it up, and you can tweak and refine the jump animations later. You could make several types of jump animations based on object near the target etc.
I would also change this stuff:
if(character.currentLabel != "walkingRight")
By defining a new function where you have all the rules for when and where something can be done, so that in your control logic, you just call
if(characterCan(character,"walkright")) ...
Where characterCan(String) is a method that check if this is possible. For instance, if you are jumping and shooting, you obviously cannot walk right, so in the end, you will have to start adding pieces of logic into those if statements and it's gonna become a cluttered mess.
A very simple approach is to have a vertical speed as well as a horizontal speed.
When the user presses "UP" or "JUMP", set y speed to a negative value and update it in your movieClip function. When the character gets to a certain height, reverse the speed.
Using gravity and acceleration looks better but this is a really good place to start. Look into kinematic equations to see how you would make the character accelerate.
public var originalY;
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.UP && vSpeed == 0)
{
originalY = character.y;
ySpeed = -1;
}
}
public function moveClip(event:TimerEvent):void
{
if (vSpeed != 0)
{
character.y += vSpeed;
/* make the character fall down after reaching max jump height */
if(originalY - character.y > jumpHeight) {
vSpeed = vSpeed * -1;
}
/* level the character after he's hit the ground (so he doesn't go through) */
else if(character.y >= originalY) {
character.y = originalY;
vSpeed = 0;
}
}
}