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? - actionscript-3

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.

Related

Actionscript 3 error 1009: Cannot access a property or method of a null object reference

I'm trying to make a simple game on Animate CC. Everything seems to work fine except when I look in the output, I get the following error:
TypeError: Error #1009: Cannot access a property or method of a null
object reference.
at _2D_CW2_Game_v10_8_fla::MainTimeline/move()
at _2D_CW2_Game_v10_8_fla::MainTimeline/updateOb()
So I know where the issue might be, and I've been trying tweaking the code for days, googling possible solutions, but to no avail...
My entire source code is as below. Any feedback/suggestions will be greatly appreciated.
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundMixer;
//==================================================
// Variable declaration
//==================================================
// defines the variables for boundaries
var left:Number = 0;
var top:Number = 0;
var right:Number = stage.stageWidth;
var bottom:Number = stage.stageHeight;
var velX:Number = 0;
var velY:Number = 0;
var gravity:Number = 1;
var friction:Number = 0.8;
var bounce:Number = -0.5;
var score:Number = 2;
var cv:Number = 0;
var curCount:Number = 30; // countdown 30s
var rightKeyDown:Boolean = false;
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var touchGround:Boolean = false;
// create and place player object on stage
var player:Player = new Player();
player.x = 110;
player.y = 460;
addChild(player);
// create obstacle array
var obstacles:Array = new Array();
var numOb:Number = 3;
// create and place enemies on stage
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = new Npc();
ob.x = 800;
ob.y = 470;
ob.scaleX = -1;
ob.vx = Math.random() * 20 + 1;
addChild(ob);
obstacles.push(ob);
}
//==================================================
// Event handlers
//==================================================
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
addEventListener(Event.ENTER_FRAME, updateOb);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
//==================================================
// Functions
//==================================================
function keyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = true;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = true;
}
if (e.keyCode == Keyboard.UP) {
// if player isn't already jumping and is on the ground
if (!upKeyDown && touchGround) {
// then start jumping
isJumping();
}
upKeyDown = true;
}
}
function keyUp(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightKeyDown = false;
}
if (e.keyCode == Keyboard.LEFT) {
leftKeyDown = false;
}
if (e.keyCode == Keyboard.UP) {
upKeyDown = false;
}
}
function EntFrame(e:Event):void {
player.x += velX;
player.y += velY;
velX *= friction;
velY += gravity;
if (player.y >= 450) {
touchGround = true;
player.y = 450;
}
// boundary checks
if (player.x + player.width/2 > right) {
player.x = right - player.width/2;
player.velX *= bounce;
} else if (player.x - player.width/2 < left) {
player.x = left + player.width/2;
player.velX *= bounce;
}
// make player move left or right
controls();
if (curCount > 0) {
cv++;
if (cv >= 30) {
curCount--;
cv = 0;
timertext.text = String(curCount);
if (curCount == 0) {
restart();
gotoAndStop("gameOverWon");
}
}
}
}
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < numOb; i++) {
var ob:Npc = obstacles[i];
move(ob);
if (player.hitTestObject(obstacles[i])) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y - player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y + player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y - player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}
// applies basic velocity to enemies
function move(moveOb) {
moveOb.x -= moveOb.vx;
if (moveOb.x + moveOb.width/2 > right) {
moveOb.x = right - moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = -1;
}
if (moveOb.x - moveOb.width/2 < left) {
moveOb.x = left + moveOb.width/2;
moveOb.vx *= bounce;
moveOb.scaleX = 1;
}
}
function bumpOb(p) {
if (p) {
p.removeEventListener(Event.ENTER_FRAME, updateOb);
if (p.parent) {
removeChild(p);
score--;
}
}
}
function restart() {
if(contains(player)) {
removeChild(player);
}
for (var i:int = 0; i < numOb; i++) {
if (contains(obstacles[i]) && obstacles[i] != null) {
removeChild(obstacles[i]);
obstacles[i] = null;
}
}
// returns a new array that consists of a range of elements from the original array,
// without modifying the original array
obstacles.slice(0);
}
function controls() {
if (rightKeyDown) {
velX += 3;
player.scaleX = 1;
}
if (leftKeyDown) {
velX -= 3;
player.scaleX = -1;
}
}
function isJumping() {
touchGround = false;
velY = -15;
}
//==================================================
// Sound control for background music
//==================================================
btnMute.addEventListener(MouseEvent.CLICK, mute);
function mute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(0);
btnMute.removeEventListener(MouseEvent.CLICK, mute);
btnMute.addEventListener(MouseEvent.CLICK, unmute);
}
function unmute(e:MouseEvent):void {
SoundMixer.soundTransform = new SoundTransform(1);
btnMute.removeEventListener(MouseEvent.CLICK, unmute);
btnMute.addEventListener(MouseEvent.CLICK, mute);
}
I had the same problem when I created interactive elements for animation. Check which layer the interactive object is on. A similar error occurred when the object overlapped something that was located on the layer above.
You can try...
1) Your Npc is a class/library object, right?
Give the source MC/Sprite, the instance name of moveOb or p.
2) or else try... Use function parameters (this is a better coding style):
(2a) Since you say..
var ob:Npc = obstacles[i];
move(ob);
ps: why not simplify (without var) as : move( obstacles[i] ); ...?
(2b) Your move function should specify a data type together with your parameter name...
//# applies basic velocity to enemies
//# Wrong...
//function move(moveOb) {
//# Better...
function move( moveOb : Npc ) {
//# Aso fix as...
function bumpOb(p : Npc ) {
By using function parameters, you can now give unique names to the (function's) input parameters but stay referencing the same (or compatible) data type.
Let me know how it goes.
The obstacles array may have null elements in the middle. What if you add a condition to continue if it's null?
function updateOb(e:Event):void {
// make obstacles move
for (var i:Number = 0; i < obstacles.length; i++) {
var ob:Npc = obstacles[i];
if(!ob) continue;
move(ob);
if (player.hitTestObject(ob)) {
/*if (obstacles[i].hitTestPoint(player.x + player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x + player.width/2, player.y -
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y +
player.height/2, true)
|| obstacles[i].hitTestPoint(player.x - player.width/2, player.y -
player.height/2, true))*/
bumpOb(obstacles[i]);
}
}
scoretext.text = String(score);
if (score == 0) {
restart();
gotoAndStop("gameOverLost");
}
}

How to set only one object to spawn with a timer?

I am currently a beginner trying to learn programming with as3 so bear with me. I have this code so far and my game repeatedly spawns the Food2 (golden apple) but it does not stop. Here is my code so far:
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class Main extends MovieClip{
const speed:int = 10;
var score:int;
var vx:int;
var vy:int;
var gFood:Food;
var gFood2:Food2;
var head:SnakePart;
var SnakeDirection:String;
var snake:Array;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var myTimer:Timer = new Timer(10000,1);
public function Main(){
init();
gotoAndStop(1);
}
function init():void {
vx = 1; vy = 0;
score = 0;
snake = new Array();
SnakeDirection = "";
addFood();
myTimer.start();
head = new SnakePart();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
start1.addEventListener(MouseEvent.CLICK, startgame);
help1.addEventListener(MouseEvent.CLICK, helpplayer);
stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
}
private function startgame(event:MouseEvent):void {
gotoAndPlay(3);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
stop();
}
private function helpplayer(event:MouseEvent):void {
gotoAndPlay(2);
stop();
}
function addFood():void {
gFood = new Food();
gFood.x = 50 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
function addFood2():void {
gFood2 = new Food2();
gFood2.x = 70 + Math.random()*(stage.stageWidth-100);
gFood2.y = 70 + Math.random()*(stage.stageHeight-100);
addChild(gFood2);
}
function reset():void {
gotoAndStop(1);
score = 0;
removeChild(gFood);
removeChild(gFood2);
myTimer.stop();
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
SnakeDirection = "left";
}else if (event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "right";
}else if (event.keyCode == Keyboard.UP) {
SnakeDirection = "up";
}else if (event.keyCode == Keyboard.DOWN) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.LEFT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.UP ) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.DOWN){
SnakeDirection = "";
}
}
function onEnterFrame(event:Event):void {
Timerfood();
txtScore.text = "Score:" + String(score);
if(SnakeDirection == "left" && vx != 1) {
vx = -1;
vy = 0;
}
else if(SnakeDirection == "right" && vx != -1) {
vx = 1;
vy = 0;
}
else if(SnakeDirection == "up" && vy != 1) {
vx = 0;
vy = -1;
}
else if(SnakeDirection == "down" && vy != -1) {
vx = 0;
vy = 1;
}
if(head.x - head.width/2 <= 0){
score = 0;
reset();
}
if(head.x + head.width/2 >= stage.stageWidth){
score = 0;
reset();
}
if(head.y - head.height/2 <= 0){
score = 0;
reset();
}
if(head.y + head.height/2 >= stage.stageHeight){
score = 0;
reset();
}
for(var i = snake.length-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
head.x += vx*speed;
head.y += vy*speed;
for(var i = snake.length-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
if(head.hitTestObject(gFood)){
score += 1;
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
score += 2;
removeChild(gFood2);
bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
function Keyboard_a(event:KeyboardEvent):void {
if (event.keyCode == 82) {
resetgame();
}
}
function resetgame():void {
score = 0;
if (contains(head))
removeChild(head);
init();
}
}
function Timerfood():void {
var myTimer:Timer = new Timer(10000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void{
trace("Timer is Triggered");
addFood2();
}
myTimer.start();
}
}
}
It's hard to understand what specific logic you want to implement, but it looks like you need to create an enemy only once. And it looks like the problem is: you call the Timerfood method in the onEnterFrame listeners, which itself is called many times per second according to the framerate of your app (e.g. 30 times per second).
I would suggest you to remove the call of Timerfood from the onEnterFrame method, and put it in the end of the init method.
Well, my English is not very good, but I try tell the possible reason,
the method Timerfood() is called on method onEnterFrame(), that initialize myTimer for each frame, so may be the solution is, remove this line into TimerFood() method:
var myTimer:Timer = new Timer(10000,1);
and call TimerFood() only in startgame() method.
I hope you can understand me.

Flash Collision Detection (Platformer game)

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.

Issues With hitTestObject in ActionScript 3

Im just trying to loop through the two arrays the bullet and enemies array then i perform the hitTestObject on both but it doesnt seem to work until the enemy gets really close to the player or bullet.
here is my code sorry that my code is sloppy `
// ******* 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;
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();
testCollisions();
}
}
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 = 288;
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;
}
}
//Check for collisions between an enemies array and a Lasers array
function testCollisions():void
{
var tempEnemy:MovieClip;
var tempLaser:MovieClip;
Enemy: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);
trace("BULLET HIT");
break Enemy;
} else if(tempEnemy.hitTestObject(player)){
removeChild(tempEnemy);
trace("HIT PLAYER");
}
}
}
}
`
It looks as though you're only checking for collisions when the shoot button is pressed, which would explain why it's not happening quickly. I suspect you want to run testCollisions every frame instead:
stage.addEventListener(Event.ENTER_FRAME, testCollisions);

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.