Flash Collision Detection (Platformer game) - actionscript-3

I am trying to make a platformer game in flash, using ActionScript 3. Currently everything is working except for one thing.
The Problem:
When the player collides with the bottom of a platform, if his xVel is not equal to zero, the horizontal collision detection loop is called and the player is moved horizontally as well as vertically. This means he bounces off the platform from underneath but is also displaced to one side of the platform. If the player's xVel is equal to zero, everything works fine. This is because the horizontal collision loop is not called. I cannot figure out why this happens. Any help would be greatly appreciated.
The Code:
import flash.events.Event;
import flash.geom.Rectangle;
var level:Array = new Array();
var xVel = 0;
var yVel = 0;
var xSpeed = 15;
var accel =1.5;
var grav = 2;
var jumpHeight = 15*grav;
for(var i = 0; i<numChildren;i++){
if(getChildAt(i) is platform){
level.push(getChildAt(i).getRect(this));
}
}
var upKeyDown = false;
var leftKeyDown = false;
var rightKeyDown = false;
var downKeyDown = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUp);
stage.addEventListener(Event.ENTER_FRAME,gameLoop);
function keyDown(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
upKeyDown = true;
}
if(e.keyCode == Keyboard.LEFT){
leftKeyDown = true;
}
if(e.keyCode == Keyboard.RIGHT){
rightKeyDown = true;
}
if(e.keyCode == Keyboard.DOWN){
downKeyDown = true;
}
}
function keyUp(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
upKeyDown = false;
}
if(e.keyCode == Keyboard.LEFT){
leftKeyDown = false;
}
if(e.keyCode == Keyboard.RIGHT){
rightKeyDown = false;
}
if(e.keyCode == Keyboard.DOWN){
downKeyDown = false;
}
}
function gameLoop(e:Event){
if(rightKeyDown){
if(xVel<xSpeed){
xVel+=accel;
}
}else if(leftKeyDown){
if(xVel>-xSpeed){
xVel-=accel;
}
}else{
xVel *=0.6;
}
//horizontal
player.x+=xVel;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(xVel>0){
player.x = level[i].left-player.width/2;
}
if(xVel<0){
player.x = level[i].right+player.width/2;
}
xVel = 0;
}
}
yVel+=grav;
player.y+=yVel;
var jumpable = false;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(yVel>0){
player.y = level[i].top-player.height/2;
yVel = 0;
jumpable = true;
}
if(yVel<0){
player.y = level[i].bottom+player.height/2;
yVel*=-0.5;
}
}
}
if(upKeyDown&&jumpable){
jump();
}
this.x = -player.x+(stage.stageWidth/2);
this.y = -player.y+(stage.stageHeight/2);
}
function jump(){
yVel-=jumpHeight;
}
Where I think the problem occurs
player.x+=xVel;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(xVel>0){
player.x = level[i].left-player.width/2;
}
if(xVel<0){
player.x = level[i].right+player.width/2;
}
xVel = 0;
}
}
yVel+=grav;
player.y+=yVel;
var jumpable = false;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(yVel>0){
player.y = level[i].top-player.height/2;
yVel = 0;
jumpable = true;
}
if(yVel<0){
player.y = level[i].bottom+player.height/2;
yVel*=-0.5;
}
}
}
The picture!
Extra information:
The platforms are movie clip symbols, all originating from the same symbol. They are dragged onto the canvas and re sized. The platform symbol has an AS linkage called 'platform' which is how the child is identified as a platform in the code
The player is a rectangle with no animations
Both the platforms and player have an orientation in the center of the object.

What you need to to is test the ceiling collision first and adjust accordingly before the horizontal check. If you don't, then you player is colliding with the bottom of the platform when you do the horizontal check.

Related

AS3 Restrict ship in visible stage area

Hey so i've been making a space shooter game and i created the movement but i'm trying to restricting the ship to the visible stage area and i can't figure out how to do that
also i'm sorry if my code it's really messy i'm really new at this
the stage size it's 1920 x 1080
here's the code of the movement
var leftKeyPressed: Boolean = false;
var rightKeyPressed: Boolean = false;
var upKeyPressed: Boolean = false;
var downKeyPressed: Boolean = false;
var xMoveSpeed: Number = 15;
var yMoveSpeed: Number = 15;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyDownHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT)
{
leftKeyPressed = true;
}
if (e.keyCode == Keyboard.RIGHT)
{
rightKeyPressed = true;
}
if (e.keyCode == Keyboard.UP)
{
upKeyPressed = true;
}
if (e.keyCode == Keyboard.DOWN)
{
downKeyPressed = true;
}
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
function keyUpHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT)
{
leftKeyPressed = false;
}
if (e.keyCode == Keyboard.RIGHT)
{
rightKeyPressed = false;
}
if (e.keyCode == Keyboard.UP)
{
upKeyPressed = false;
}
if (e.keyCode == Keyboard.DOWN)
{
downKeyPressed = false;
}
}
stage.addEventListener(Event.ENTER_FRAME, moveHero);
function moveHero(e: Event): void
{
if (leftKeyPressed)
{
ship.x -= xMoveSpeed;
}
if (rightKeyPressed)
{
ship.x += xMoveSpeed;
}
if (upKeyPressed)
{
ship.y -= yMoveSpeed;
}
if (downKeyPressed)
{
ship.y += yMoveSpeed;
}
}
Well, you can start with this.
// One map is much better than a separate variable for each and every key.
var keyMap:Object = new Object;
// Initial keymap values.
keyMap[Keyboard.UP] = 0;
keyMap[Keyboard.DOWN] = 0;
keyMap[Keyboard.LEFT] = 0;
keyMap[Keyboard.RIGHT] = 0;
// With the keymap you don't need these big event handlers,
// you need a single one with one line of code.
stage.addEventListener(KeyboardEvent.KEY_DOWN, onUpDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUpDown);
function onUpDown(e:KeyboardEvent):void
{
// The members of the object with the names of key codes
// will be set to 1 in case of KEY_DOWN event or 0 in case of KEY_UP.
keyMap[e.keyCode] = int(e.type == KeyboardEvent.KEY_DOWN);
}
stage.addEventListener(Event.ENTER_FRAME, moveHero);
// This will provide you with min and max values for both X and Y coordinates.
// You will probably need to adjust it because the ship have width and height.
var conStraints:Rectangle = new Rectangle(0, 0, 1920, 1080);
var xMoveSpeed:Number = 15;
var yMoveSpeed:Number = 15;
function moveHero(e:Event):void
{
var anX:Number = ship.x;
var anY:Number = ship.y;
// Use keymap to figure the new coordinates.
// Take into account all the relevant keys pressed.
anX += xMoveSpeed * (keyMap[Keyboard.RIGHT] - keyMap[Keyboard.LEFT]);
anY += yMoveSpeed * (keyMap[Keyboard.DOWN] - keyMap[Keyboard.UP]);
// Now set the new ship coordinates with the regard to constraints.
ship.x = Math.min(conStraints.right, Math.max(conStraints.left, anX));
ship.y = Math.min(conStraints.bottom, Math.max(conStraints.top, anY));
}
I think this is the easiet solution, tell me if it worked or not
function keyDownHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT && ship.x > 15)
{
leftKeyPressed = true;
}
if (e.keyCode == Keyboard.RIGHT && ship.x < 1905)
{
rightKeyPressed = true;
}
if (e.keyCode == Keyboard.UP && ship.y > 15)
{
upKeyPressed = true;
}
if (e.keyCode == Keyboard.DOWN && ship.y < 1065)
{
downKeyPressed = true;
}
}

Character Jump with Animation

Im trying to create a platform game but im struggling with the jump part of the game. I have got the jump working but when I try to add the animation it goes all wrong. When I hit the jump button it jumps but when i lands it gets stuck on the end of the jump animation until i move. Secondly when i jump and press the right or left button it jumps but plays the run animation while i try to move in mid air. How can i resolve these problems
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Player extends MovieClip
{
//Player run speed setting
var RunSpeed:Number = 8;
//Player key presses
var RightKeyPress:Boolean = false;
var LeftKeyPress:Boolean = false;
var UpKeyPress:Boolean = false;
//Jump variables
var Gravity:Number = 1.5;
var Yvelocity:Number = 0;
var CanJump:Boolean = false;
public function Player()
{
// constructor code
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);
addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_UP, KeyReleased);
}
function KeyPressed(event:KeyboardEvent)
{
//When Key is Down
if (event.keyCode == 39)
{
RightKeyPress = true;
}
if (event.keyCode == 37)
{
LeftKeyPress = true;
}
if (event.keyCode == 38)
{
UpKeyPress = true;
}
}
function Update(event:Event)
{
//Adding gravity to the game world
Yvelocity += Gravity;
//if player is more than 300 on the y-axis
if (this.y > 300)
{
//Player stays on the ground and can jump
Yvelocity = 0;
CanJump = true;
}
if ((RightKeyPress == true))
{
x += RunSpeed;
gotoAndStop('Run');
scaleX = 1;
}
else if ((LeftKeyPress == true))
{
x -= RunSpeed;
gotoAndStop('Run');
scaleX = -1;
}
if ((UpKeyPress == true && CanJump))
{
Yvelocity = -15;
CanJump = false;
gotoAndStop('Jump');
}
this.y += Yvelocity;
}
function KeyReleased(event:KeyboardEvent)
{
if (event.keyCode == 39)
{
event.keyCode = 0;
RightKeyPress = false;
gotoAndStop('Idle');
}
if (event.keyCode == 37)
{
event.keyCode = 0;
LeftKeyPress = false;
gotoAndStop('Idle');
}
if (event.keyCode == 38)
{
event.keyCode = 0;
UpKeyPress = false;
}
}
}
}
this.y > 300, that is your jump end logic. Add a gotoAndStop('Idle'); in that if's block.
Just Check if canJump is true on your left and right keypresses before executing those blocks. If canJump is true allow the running stuff

How Do I spawn Enemy at either the far left or the far right of the stage and have them move in to the center?

First I get This Error
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Game_fla::MainTimeline/testCollisions()[Game_fla.MainTimeline::frame1:205]
and here is my code
// ******* IMPORTS *****
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
//*****VARIABLES****
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var shootDown:Boolean = false;
var ySpeed:int = 0;
var xSpeed:int = 0;
var scrollX:int = 0;
var scrollY:int = 0;
var speedConstant:int = 5;
var friction:Number = 0.6;
var level:Number = 1;
var bullets:Array = new Array();
var container_mc:MovieClip;
var enemies:Array;
var tempEnemy:MovieClip;
// BUTTON EVENTS EITHER CLICKED OR NOT
left_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
right_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveRight);
up_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveUp);
shoot_btn.addEventListener(MouseEvent.MOUSE_DOWN, shootPressed);
left_btn.addEventListener(MouseEvent.MOUSE_UP, leftUp);
right_btn.addEventListener(MouseEvent.MOUSE_UP, rightUp);
up_btn.addEventListener(MouseEvent.MOUSE_UP, upUp);
stage.addEventListener(Event.ENTER_FRAME, makeEnemies);
player.gotoAndStop('still');
stage.addEventListener(Event.ENTER_FRAME,onenter);
function onenter(e:Event):void{
if (rightPressed == true && leftPressed == false){
player.x += 8;
player.scaleX = 1;
player.gotoAndStop("walking");
cloud.x -= 8;
} else if (leftPressed == true && rightPressed == false){
player.x -= 8;
player.scaleX = -1;
player.gotoAndStop('walking');
cloud.x += 8;
} else if(upPressed == true && leftPressed == false && rightPressed == false){
}
else{
rightPressed = false;
leftPressed = false;
player.gotoAndStop('still')}
}
// **** MOVEMENT CONTROLS *********
function shootPressed(e:MouseEvent):void{
shootDown = true;
if(shootDown == true){
fireBullet();
}
}
function fireBullet():void
{
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
var bullet:Bullet = new Bullet(player.x, player.y, playerDirection);
//bullets = new Array();
bullet.y = player.y + 8;
stage.addChild(bullet);
bullets.push(bullet);
trace(bullets);
}
// BUTTON FUNCTIONS
function moveLeft(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
leftPressed = true;
}else if (MouseEvent.MOUSE_UP) {
leftPressed = false;
}
}
function moveRight(e:MouseEvent):void
{
if (MouseEvent.MOUSE_DOWN){
rightPressed = true;
}else if (MouseEvent.MOUSE_UP){
rightPressed = false;
}
}
function moveUp(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
upPressed = true;
} else if (MouseEvent.MOUSE_UP) {
upPressed = false;
}
}
function leftUp(e:MouseEvent):void
{
leftPressed = false;
}
function rightUp(e:MouseEvent):void
{
rightPressed = false;
}
function upUp(e:MouseEvent):void
{
upPressed = false;
}
enemies = new Array();
//Call this function for how many enemies you want to make...
function makeEnemies(e:Event):void
{
var chance:Number = Math.floor(Math.random() * 60);
if (chance <= 2){
//Make sure a Library item linkage is set to Enemy...
tempEnemy = new enemy();
tempEnemy.speed = 80;
tempEnemy.x = Math.round(Math.random() * stage.stageWidth) * -10;
addChild(tempEnemy);
enemies.push(tempEnemy);
moveEnemies();
}
}
function moveEnemies():void
{
var tempEnemy:MovieClip;
for (var i:int =enemies.length-1; i>=0; i--)
{
tempEnemy = enemies[i];
tempEnemy.x += tempEnemy.speed;
tempEnemy.y = 285;
}
}
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
//Check for collisions between an enemies array and a Lasers array
function testCollisions(e:Event):void
{
var tempEnemy:MovieClip;
var tempLaser:MovieClip;
for (var i:int=enemies.length-1; i >= 0; i--)
{
tempEnemy = enemies[i];
for (var j:int=bullets.length-1; j>=0; j--)
{
tempLaser = bullets[j];
if (tempLaser.hitTestObject(tempEnemy))
{
removeChild(tempEnemy);
removeChild(tempLaser);
trace("BULLET HIT");
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
}
}
}
}
I Understand that I need to reference the parent whenever I removeChild in the testCollision function but I dont know where.
Also I want the zombies to spawn out of the stage and move in towards the center at a smooth speed with the code I have they just seem to spawn sort of rearly and always to the left of the stage. So I would need to spawn them off the stage and have them move in to the center and change their ScaleX position to change their dirention but I dont know how to do that Please help.
I think you can fix the error you listed by changing removeChild(tempLaser) to stage.removeChild(tempLaser) since the stage is where you added your bullets, so that's where you need to remove them from.
I'll give you a hint on the zombie movement, but you'll probably want to find a programming forum/friend/professor to help with general code design questions like this. In moveEnemies, you'll need to decide whether the zombie should move left/right (based on whether their x position is larger or smaller than the player's), and whether they should move up/down (based on whether their y position is larger or smaller than the player's).
For example, if their x position is larger than the player's, you would do tempEnemy.x -= tempEnemy.speed, and if smaller, you would do tempEnemy.x += tempEnemy.speed. But as I said, this site isn't really made for these types of design questions.

1180: Call to a possibly undefined method Player

I was trying to code the code below into a package that came from a tutorial, but it originally had it in the timeline
now it gives the error 1180: Call to a possibly undefined method Player.
here is a snippet from the concerning code (full code is below that)
private var player:Player;
public function RamboCat()
{
player = new Player();
So Player is not defined. Does this mean it's missing a AS file or something
But i'm trying to tell flash to use a image (image is instanced 'player')
i added the above code (minus the public function that already existed) because i found
a source which explained i should add those: http://www.actionscript.org/forums/showthread.php3?t=268065
my experience with "package" and "import" things is a bit low. So hopefully you can help.
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.Point;
public class RamboCat extends MovieClip
{
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftBumping:Boolean = false;
var rightBumping:Boolean = false;
var upBumping:Boolean = false;
var downBumping:Boolean = false;
var leftBumpPoint:Point = new Point(-30, -55);
var rightBumpPoint:Point = new Point(30, -55);
var upBumpPoint:Point = new Point(0, -120);
var downBumpPoint:Point = new Point(0, 0);
var scrollX:Number = 0;
var scrollY:Number = 500;
var xSpeed:Number = 0;
var ySpeed:Number = 0;
var speedConstant:Number = 4;
var frictionConstant:Number = 0.9;
var gravityConstant:Number = 1.8;
var jumpConstant:Number = -35;
var maxSpeedConstant:Number = 18;
var doubleJumpReady:Boolean = false;
var upReleasedInAir:Boolean = false;
var keyCollected:Boolean = false;
var doorOpen:Boolean = false;
var currentLevel:int = 1;
var animationState:String = "idle";
var bulletList:Array = new Array();
var enemyList:Array = new Array();
var bumperList:Array = new Array();
private var player:Player;
public function RamboCat()
{
player = new Player();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, loop);
addEnemiesToLevel1();
addBumpersToLevel1();
}
public function addEnemiesToLevel1():void
{
addEnemy(620, -115);
addEnemy(900, -490);
addEnemy(2005, -115);
addEnemy(1225, -875);
}
public function addBumpersToLevel1():void
{
addBumper(500, -115);
addBumper(740, -115);
}
public function loop(e:Event):void{
if(back.collisions.hitTestPoint(player.x + leftBumpPoint.x, player.y + leftBumpPoint.y, true)){
//trace("leftBumping");
leftBumping = true;
} else {
leftBumping = false;
}
if(back.collisions.hitTestPoint(player.x + rightBumpPoint.x, player.y + rightBumpPoint.y, true)){
//trace("rightBumping");
rightBumping = true;
} else {
rightBumping = false;
}
if(back.collisions.hitTestPoint(player.x + upBumpPoint.x, player.y + upBumpPoint.y, true)){
//trace("upBumping");
upBumping = true;
} else {
upBumping = false;
}
if(back.collisions.hitTestPoint(player.x + downBumpPoint.x, player.y + downBumpPoint.y, true)){
//trace("downBumping");
downBumping = true;
} else {
downBumping = false;
}
if(leftPressed){
xSpeed -= speedConstant;
player.scaleX = -1;
} else if(rightPressed){
xSpeed += speedConstant;
player.scaleX = 1;
}
/*if(upPressed){
ySpeed -= speedConstant;
} else if(downPressed){
ySpeed += speedConstant;
}*/
if(leftBumping){
if(xSpeed < 0){
xSpeed *= -0.5;
}
}
if(rightBumping){
if(xSpeed > 0){
xSpeed *= -0.5;
}
}
if(upBumping){
if(ySpeed < 0){
ySpeed *= -0.5;
}
}
if(downBumping){ //if we are touching the floor
if(ySpeed > 0){
ySpeed = 0; //set the y speed to zero
}
if(upPressed){ //and if the up arrow is pressed
ySpeed = jumpConstant; //set the y speed to the jump constant
}
//DOUBLE JUMP
if(upReleasedInAir == true){
upReleasedInAir = false;
}
if(doubleJumpReady == false){
doubleJumpReady = true;
}
} else { //if we are not touching the floor
ySpeed += gravityConstant; //accelerate downwards
//DOUBLE JUMP
if(upPressed == false && upReleasedInAir == false){
upReleasedInAir = true;
//trace("upReleasedInAir");
}
if(doubleJumpReady && upReleasedInAir){
if(upPressed){ //and if the up arrow is pressed
//trace("doubleJump!");
doubleJumpReady = false;
ySpeed = jumpConstant; //set the y speed to the jump constant
}
}
}
if(keyCollected == false){
if(player.hitTestObject(back.other.doorKey)){
back.other.doorKey.visible = false;
keyCollected = true;
trace("key collected");
}
}
if(doorOpen == false){
if(keyCollected == true){
if(player.hitTestObject(back.other.lockedDoor)){
back.other.lockedDoor.gotoAndStop(2);
doorOpen = true;
trace("door open");
}
}
}
if(xSpeed > maxSpeedConstant){ //moving right
xSpeed = maxSpeedConstant;
} else if(xSpeed < (maxSpeedConstant * -1)){ //moving left
xSpeed = (maxSpeedConstant * -1);
}
xSpeed *= frictionConstant;
ySpeed *= frictionConstant;
if(Math.abs(xSpeed) < 0.5){
xSpeed = 0;
}
scrollX -= xSpeed;
scrollY -= ySpeed;
back.x = scrollX;
back.y = scrollY;
sky.x = scrollX * 0.2;
sky.y = scrollY * 0.2;
if( ( leftPressed || rightPressed || xSpeed > speedConstant || xSpeed < speedConstant *-1 ) && downBumping){
animationState = "running";
} else if(downBumping){
animationState = "idle";
} else {
animationState = "jumping";
}
if(player.currentLabel != animationState){
player.gotoAndStop(animationState);
}
if (enemyList.length > 0) // if there are any enemies left in the enemyList
{
for (var i:int = 0; i < enemyList.length; i++) // for each enemy in the enemyList
{
if (bulletList.length > 0) // if there are any bullets alive
{
for (var j:int = 0; j < bulletList.length; j++) // for each bullet in the bulletList
{
if ( enemyList[i].hitTestObject(bulletList[j]) )
{
trace("Bullet and Enemy are colliding");
enemyList[i].removeSelf();
bulletList[j].removeSelf();
}
// enemyList[i] will give you the current enemy
// bulletList[j] will give you the current bullet
// this will check all combinations of bullets and enemies
// and see if any are colliding
}
}
}
}
//corralling the bad guys with bumpers
if (enemyList.length > 0){ //enemies left in the enemyList?
for (var k:int = 0; k < enemyList.length; k++){ // for each enemy in the enemyList
if (bumperList.length > 0){
for (var h:int = 0; h < bumperList.length; h++){ // for each bumper in the List
if ( enemyList[k].hitTestObject(bumperList[h]) ){
enemyList[k].changeDirection();
}
}
}
}
}
//player and enemy collisions
if (enemyList.length > 0){ //enemies left?
for (var m:int = 0; m < enemyList.length; m++){ // for each enemy in the enemyList
if ( enemyList[m].hitTestObject(player) ){
trace("player collided with enemy");
//code to damage player goes here, maybe integrate with a health bar?
enemyList[m].removeSelf();
}
}
}
}
public function nextLevel():void{
currentLevel++;
trace("Next Level: " + currentLevel);
if(currentLevel == 2){
gotoLevel2();
}
// can be extended...
// else if(currentLevel == 3) { gotoLevel3(); } // etc, etc.
}
public function gotoLevel2():void{
back.other.gotoAndStop(2);
back.visuals.gotoAndStop(2);
back.collisions.gotoAndStop(2);
scrollX = 0;
scrollY = 500;
keyCollected = false;
back.other.doorKey.visible = true;
doorOpen = false;
back.other.lockedDoor.gotoAndStop(1);
}
public function keyDownHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = true;
} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = true;
} else if(e.keyCode == Keyboard.UP){
upPressed = true;
} else if(e.keyCode == Keyboard.DOWN){
downPressed = true;
if(doorOpen && player.hitTestObject(back.other.lockedDoor)){
//proceed to the next level if the player is touching an open door
nextLevel();
}
}
}
public function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = false;
} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = false;
} else if(e.keyCode == Keyboard.UP){
upPressed = false;
} else if(e.keyCode == Keyboard.DOWN){
downPressed = false;
}
if(e.keyCode == Keyboard.SPACE){
fireBullet();
}
}
public function fireBullet():void
{
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
var bullet:Bullet = new Bullet(player.x - scrollX, player.y - scrollY, playerDirection, xSpeed);
back.addChild(bullet);
bullet.addEventListener(Event.REMOVED, bulletRemoved);
bulletList.push(bullet);
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED, bulletRemoved); //this just removes the eventListener so we don't get an error
bulletList.splice(bulletList.indexOf(e.currentTarget), 1);
//this removes 1 object from the bulletList, at the index of whatever object caused this function to activate
}
public function addEnemy(xLocation:int, yLocation:int):void
{
var enemy:Enemy = new Enemy(xLocation, yLocation);
back.addChild(enemy);
enemy.addEventListener(Event.REMOVED, enemyRemoved);
enemyList.push(enemy);
}
public function addBumper(xLocation:int, yLocation:int):void
{
var bumper:Bumper = new Bumper(xLocation, yLocation);
back.addChild(bumper);
bumper.visible = false;
bumperList.push(bumper);
}
public function enemyRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED, enemyRemoved);
//this just removes the eventListener so it doesn't give an error
enemyList.splice(enemyList.indexOf(e.currentTarget), 1); //this removes 1 object from the enemyList, at the index of whatever object caused this function to activate
}
}
}
It cannot be a reference to an instance of player as: new Player(); creates a new instance of Player.
So Player needs to be a class. If you are using Adobe Flash Professional, you can right click the image in the library, click properties, actionscript tab, then export to actionscript (make sure the class is called Player). this will create the class for the image for you.
If you are not using Adobe flash professional, then let me know and I will help with the IDE you are using.
Edit: And looking back you will also need to import Keyboard Class if you have not done already.
Looks like you need an import statement for Player.
To import a single class:
import your.package.name.ClassName;
To import every class in a package:
import your.package.name.*;
So you need:
import xxx.Player;
where xxx is the package where Player class sits.

addEventListener() isn't detecting KEY_UP nor KEY_DOWN

My full code is
import flash.events.KeyboardEvent;
import flash.events.Event;
//init some variables
var speedX = 0;
var speedY = 0;
msg.visible = false;
var curLevel = 2;
var level = new Array();
var flagVar;
var won = false;
//Adding level platforms
for(var i = 0; i < numChildren; i++) {
if(getChildAt(i) is platform) {
level.push(getChildAt(i).getRect(this));
}
if(getChildAt(i) is flag) { flagVar = getChildAt(i).getRect(this); }
}
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
addEventListener(Event.ENTER_FRAME, loopAround);
function loopAround(e:Event) {
//horizontal movement
if(kLeft) {
speedX = -10;
} else if(kRight) {
speedX = 10;
} else {
speedX *= 0.5;
}
player.x += speedX;
//horizontal collision checks
for(var i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedX > 0) {
player.x = level[i].left - player.width;
}
if(speedX < 0) {
player.x = level[i].right;
}
speedX = 0;
}
}
//vertical movement
speedY += 1;
player.y += speedY;
var jumpable = false;
//Vertical collision
for(i = 0; i < level.length; i++) {
if(player.getRect(this).intersects(level[i])) {
if(speedY > 0) {
player.y = level[i].top - player.height;
speedY = 0;
jumpable = true;
}
if(speedY < 0) {
player.y = level[i].bottom;
speedY *= -0.5;
}
}
}
//JUMP!
if((kUp || kSpace) && jumpable) {
speedY=-20;
}
//Moving camera and other
this.x = -player.x + (stage.stageWidth/2);
this.y = -player.y + (stage.stageHeight/2);
msg.x = player.x - (msg.width/2);
msg.y = player.y - (msg.height/2);
//Checking win
if(player.getRect(this).intersects(flagVar)) {
msg.visible = true;
won = true;
}
//Check for next level request
if(kSpace && won) {
curLevel++;
gotoAndStop(curLevel);
won = false;
}
}
The section in question is
//Checking key presses
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
var kSpace = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent) {
trace("Key down - " + k.keyCode);
if(k.keyCode == 32) { kSpace = true; }
if(k.keyCode == 37 ) { kLeft = true; }
if(k.keyCode == 38) { kUp = true; }
if(k.keyCode == 39) { kRight = true; }
}
function kU(k:KeyboardEvent) {
trace("Key up - " + k.keyCode);
if(k.keyCode == 32) { kSpace = false; }
if(k.keyCode == 37) { kLeft = false; }
if(k.keyCode == 38) { kUp = false; }
if(k.keyCode == 39) { kRight = false; }
}
This was working fine last night, but today I moved it to a new keyframe and now it's not working. I'm not getting any errors (even if I debug). It just won't move the character or even show up in output.
I'm still quite new to as3, so I don't really know what to do.
Thanks in advance.
Edit: After playing with it a bit, I've found out that the reason it's not working is due to the menu. The menu has a single button and two text elements, which are fine. The code that I'm using on the menu is this:
import flash.events.MouseEvent;
stop();
var format:TextFormat = new TextFormat();
format.size = 26;
format.bold = true;
playGameButton.setStyle("textFormat", format);
stage.addEventListener(MouseEvent.CLICK, playGame);
function playGame(e:MouseEvent) {
if(e.target.name == "playGameButton") {
gotoAndStop(2);
}
}
If I use just gotoAndStop(2); it works fine, but with everything else it just goes to the second frame, and nothing else works after that.
Edit #2: I've narrowed it down even farther to the if statement itself.
if(e.target == playGameButton)
if(e.target.name == "playGameButton")
Both of those don't work. If I just remove the if statement all together it works perfectly fine.
there seems to be aproblem with this lines
if(getChildAt(i) is platform)
leads to error 1067: Implicit coercion of a value of type flash.display:MovieClip to an unrelated type Class
the rest of the code seems to be just fine
Try disabling your buttons mouseChildren.
playGameButton.mouseChildren = false;
Try e.currentTarget instead of e.target. From the documentation:
currentTarget : Object
[read-only] The object that is actively processing the Event object with an event listener.
target : Object
[read-only] The event target.
I'm not quite sure that this is your problem but the target vs currentTarget confusion has gotten me before.