I have a variable on frame 1 that starts at 3000 and keeps decreasing. This variable determines the gap of time between the spawn of an object. so basically the objects spawn quicker and quicker as the this number decreases. Everything works fine except the fact when i make the character die and the main timeline goes to frame 2 to show the death screen. When clicked "play again" on that frame that makes you come back to frame 1. the objects keep spawning at whatever speed they were spawning before death. Even though the variable resets to 3000 when "play again" clicked..
I traced the variable and it does truely reset. but for some reason those spawning objects follow the previous variable.
Heres the code on the first Frame:
import flash.events.Event;
stop();
var num1:Number = 0;
var scrollSpeed:Number = 3000;
var playerState:Number = 1;
var alive:Boolean = true;
var Redbars:Array = new Array();
var Bluebars:Array = new Array();
var scoreCount:Number = 10;
addEventListener(Event.ENTER_FRAME, update);
function update(e:Event){
trace(scrollSpeed);
scoreCount += 1;
scoreText.text = (scoreCount).toString();
//SCROLL SPEED-------------------
if(scrollSpeed > 300)
{
scrollSpeed -= 1;
}
//--------------------------------
CheckForCollisionBlue();
CheckForCollisionRed();
//trace(alive);
if(player.currentFrame == 1){
playerState = 1;
}
//Check if lost
if(player.hitTestObject(leftHitBox)){
gotoAndStop(2);
scoreEnd.text = (scoreCount).toString();
}
//If dead Delete Object
if(currentFrame == 2){
deleteBlue();
deleteRed();
}
}
////
//Timer////////////////////////////////
var myTimer:Timer = new Timer(scrollSpeed,10000000);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
//Generate Random number
num1 = randomRange();
trace(num1);
//IF NUM1 = 1------------------------------------------
if(num1 == 1){
//Create a Red Bar
var redBar = new Jump_Cube();
Redbars.push(redBar); //add enemy to the array
redBar.x = -33;
redBar.y = 99;
redBar.width = 12.5;
redBar.height = 20.45;
//Update the Bar
for(var i:int=0; i < Redbars.length; i++){
if(currentFrame == 1)
{
addChild(Redbars[i]);
}
}
}
//IF NUM1 = 2------------------------------------------
if(num1 == 2){
//Create a Blue Bar
var blueBar = new Jump_Cube2();
Bluebars.push(blueBar); //add enemy to the array
blueBar.x = -26.8;
blueBar.y = 10;
blueBar.width = 12.25;
blueBar.height = 31.90;
//Update the Bar
for(var j:int=0; j < Bluebars.length; j++){
if(currentFrame == 1)
{
addChild(Bluebars[j]);
}
}
myTimer.delay = scrollSpeed;
}
}
myTimer.start();
//--------------------------------------------------------------------
//Check for Collision------------------------------
function CheckForCollisionBlue(){
for(var i:int=0; i < Bluebars.length; i++){
if( player.hitTestObject(Bluebars[i]) ){
//Collision
trace("Didnt Hit Blue");
player.x -= 5;
player.y += 1;
}
}
}
//Check for Collision------------------------------
function CheckForCollisionRed(){
for(var i:int=0; i < Redbars.length; i++){
if( player.hitTestObject(Redbars[i]) ){
//Collision
trace("Didnt Hit Red");
player.x -= 5;
player.y += 1;
}
}
}
function randomRange():Number
{
return (Math.floor(Math.random() * (2 - 1 + 1)) + 1);
}
///////////BUTTONS------------------
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
redButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndRed);
function onTouchEndRed(e:TouchEvent):void{
player.gotoAndPlay(2);
playerState = 2;
}
blueButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndBlue);
function onTouchEndBlue(e:TouchEvent):void{
player.gotoAndPlay(19);
playerState = 3;
}
///////--CLEARING STAGE
//--------------------------------------------------------------------
//delete Blue------------------------------
function deleteBlue(){
for(var i:int=0; i < Bluebars.length; i++){
removeChild(Bluebars[i]);
}
}
//delete Red------------------------------
function deleteRed(){
for(var i:int=0; i < Redbars.length; i++){
removeChild(Redbars[i]);
}
}
Heres the code on the second frame:
stop();
alive = false;
againButton.addEventListener(TouchEvent.TOUCH_END, again);
function again(e:TouchEvent):void{
gotoAndStop(1);
playerState = 1;
scrollSpeed = 3000;
deleteBlue();
deleteRed();
}
You have to put in a removeEventListener(Event.ENTER_FRAME, update); inside your onTouchEndRed function. And probably also inside of this 'if' conditional: if(player.hitTestObject(leftHitBox)){...
Simply stop programming using frames. Use classes instead. AS3 is based on classes. It'll take you a lot of benefits. This link may help you to start: http://www.adobe.com/devnet/actionscript/getting_started.html
Additionally, FlashPlayer executes frame's code each time you jump to another frame. Thats why your variables are reinitializing.
Related
Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the sheep to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);
I am making a game similar to doodle jump and I have a powerup MovieClip that appears every time the character bounces up. When the character collides with the powerup, I want it to add to the live score, and then disappear. But I want it to reappear after is has been removed so there is a constant stream of powerups (one for each time the character jumps).
The problem I'm having is that as soon as the first powerup is hit, it visually removes all future powerups but the character is still able to collide with them - constantly adding to the score rather than just once.
I made a recording that I think would help explain.
Here's the block of code I'm trying to fix:
//IF MyChicken TOUCHES CHICKEN LEG, SCORE GOES UP BY 2000
for (var c:int=0; c< 1; c++){
chickMc = powerUp[c];
if (MyChicken.hitTestObject(chickMc))
{
liveScore += 2000;
theScore.text = liveScore.toString();
tapSnd.play();
removeChild(chickMc);
}
}
In case it's something outside of this chunk, here's my whole code:
import flash.events.Event;
import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;
import flash.display.MovieClip;
import flash.media.Sound;
import flash.events.MouseEvent;
var firstPass:int = 1;
var liveScore:int;
var accX:Number;
var myVect:Vector.<MovieClip> = new Vector.<MovieClip>(5,true);
var powerUp:Vector.<MovieClip> = new Vector.<MovieClip>(1, true);
var vAcceleration:Number = 0.5;
var vVelocity:Number = -20;
var middleScreen:Number = stage.height / 2;
//var newEnemy:enemy;
//var nmeMc:MovieClip;
var newChicken:chicken;
var chickMc:MovieClip;
var newBouncer:bouncer;
var tmpMc:MovieClip;
var poolSnd:poolSound = new poolSound();
var tapSnd:tapSound = new tapSound();
var btnAgain:gameOver;
stop();
// MONITOR THE ACCELEROMETER
var myAcc:Accelerometer = new Accelerometer();
myAcc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(evt:AccelerometerEvent):void{
accX = evt.accelerationX;
}
//MONITOR THE ENTER_FRAME EVENT
stage.addEventListener(Event.ENTER_FRAME, onMyEnterFrame);
//INIT STAGE WITH PLATFORMS (bouncer)
if (firstPass == 1){
liveScore = 0;
accX = 0;
for (var i:int=0; i< 5; i++){
newBouncer = new bouncer;
newBouncer.x = Math.random()*stage.stageWidth;
newBouncer.y = 0 + i*stage.stageHeight/6;
myVect[i] = newBouncer;
addChild(newBouncer);
newBouncer.cacheAsBitmap = true;}
for (var c:int=0; c< 1; c++){
newChicken = new chicken;
newChicken.x = Math.random()*stage.stageWidth;
newChicken.y = 0 + c*stage.stageHeight/6;
powerUp[c] = newChicken;
addChild(newChicken);
newChicken.cacheAsBitmap = true;}
firstPass = 2;
}
function onMyEnterFrame(evt:Event):void{
//MOVE X DEPENDING ON THE ACCELEROMETER
MyChicken.x += (MyChicken.x - (MyChicken.x + accX * 20))*0.6;
//MOVE CHAR TO THE LEFT OR TO THE RIGHT
if(accX < 0) {
MyChicken.gotoAndStop(2);
}else{
MyChicken.gotoAndStop(1);
}
// VERTICAL SPEED OF MyChicken
vVelocity += vAcceleration;
if((MyChicken.y > middleScreen) && (vVelocity < 0)){
// MyChicken IS GOING UP
MyChicken.y += vVelocity;
}else{
if(vVelocity > 0){
// MyChicken IS GOING DOWN
MyChicken.y += vVelocity;
// TEST IF MyChicken HITS PLATFORM
for (var i:int=0; i< 5; i++){
tmpMc = myVect[i];
if (MyChicken.hitTestObject(tmpMc))
{
vVelocity = -20;
tapSnd.play();
}
}
//IF MyChicken TOUCHES CHICKEN LEG, SCORE GOES UP BY 2000
for (var c:int=0; c< 1; c++){
chickMc = powerUp[c];
if (MyChicken.hitTestObject(chickMc))
{
liveScore += 2000;
theScore.text = liveScore.toString();
tapSnd.play();
removeChild(chickMc);
}
}
}else{
// THE WORLD IS GOING DOWN
// WHEN MyChicken IS IN THE MIDDLE OF THE SCREEN
for (var m:int=0; m< 1; m++){
chickMc = powerUp[m];
chickMc.y -= vVelocity;
}
for (var j:int=0; j< 5; j++){
tmpMc = myVect[j];
tmpMc.y -= vVelocity;
}
liveScore += 5;
theScore.text = liveScore.toString();
}
}
//CHECK IF PLATFORMS ARE OUT OF THE SCREEN
if(myVect[0] != null){
for (var k:int=0; k< 5; k++){
tmpMc = myVect[k];
if(tmpMc.y > stage.stageHeight){
tmpMc.y = -5;
tmpMc.x = Math.random()*stage.stageWidth;
}
}
}
if(powerUp[0] != null){
for (var p:int=0; p< 1; p++){
chickMc = powerUp[p];
if(chickMc.y > stage.stageHeight){
chickMc.y = -5;
chickMc.x = Math.random()*stage.stageWidth;
}
}
}
//FAIL - IF CHICKEN FALLS OUT OF THE SCREEN
if (MyChicken.y > stage.stageHeight) {
btnAgain = new gameOver();
addChild(btnAgain);
btnAgain.x = 160;
btnAgain.y = 230;
btnAgain.theScoreFinal.text = liveScore.toString();
theScore.visible = false;
btnAgain.addEventListener(MouseEvent.MOUSE_DOWN, onPlayAgain);
//PAUSE GAME
MyChicken.y = -300;
vVelocity = 0;
vAcceleration = 0;
// PLAY FAIL SOUND
poolSnd.play();
}
// CLICKS ON THE PLAY AGAIN BUTTON
function onPlayAgain(evt:MouseEvent):void{
removeChild(btnAgain);
//NEW GAME
MyChicken.y = stage.stageHeight - 50;
MyChicken.x = stage.stageWidth / 2;
theScore.text = "0";
liveScore = 0;
vVelocity = -20;
vAcceleration = 0.5;
theScore.visible = true;
}
//STAGE BOUNDS MyChicken ON THE LEFT OR RIGHT OF THE SCREEN
if(MyChicken.x < 0) MyChicken.x = stage.stageWidth;
if(MyChicken.x > stage.stageWidth) MyChicken.x = 0;
}
Removing an object does not change its x/y coordinates or width/height (bounds). hitTestObject checks the two objects bounds - it does not take into consideration if an object is actually on the display tree or not. So even though you've successfully removed the object, the hit test will keep checking it. (as the object still exists, it just can't be seen)
You can remedy this by doing a check first to see if chickMc has been removed:
if (chickMc.parent && MyChicken.hitTestObject(chickMc))
The parent property of a display object will null after being removed from the stage.
Though instead of that, you may want to null the reference to the object so it can be garbage collected later:
for (var c:int=0; c< 1; c++){
chickMc = powerUp[c];
if (chickMc != null && MyChicken.hitTestObject(chickMc)){
liveScore += 2000;
theScore.text = liveScore.toString();
tapSnd.play();
removeChild(chickMc);
powerUp[c] == null; //now that powerup object isn't referenced anywhere and can be garbage collected (destroyed from memory)
}
}
I am currently trying to put together a platformer game similar to doodlejump however I am getting two errors that I am unsure of how to fix. Below is the code that I am currently using. My errors are;
**Scene 1, Layer 'Code', Frame 4, Line 181 1046: Type was not found or was not a compile-time constant: stick.
Scene 1, Layer 'Code', Frame 4, Line 207 1180: Call to a possibly undefined method stick.**
var tempStick:stick;
var tmpMc:MovieClip;
stop();
// MONITOR THE ACCELEROMETER
var myAcc:Accelerometer = new Accelerometer();
myAcc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
function onAccUpdate(evt:AccelerometerEvent):void{
accX = evt.accelerationX;
}
//MONITOR THE ENTER_FRAME EVENT
stage.addEventListener(Event.ENTER_FRAME, onMyEnterFrame);
//INIT STAGE WITH CLOUDS
if (firstPass == 1){
liveScore = 0;
accX = 0;
for (var i:int=0; i< 5; i++){
tempStick = new stick;
tempStick.x = Math.random()*stage.stageWidth;
tempStick.y = 0 + i*stage.stageHeight/6;
myVect[i] = tempStick;
addChild(tempStick);
tempStick.cacheAsBitmap = true;
}
firstPass = 2;
}
function onMyEnterFrame(evt:Event):void{
//MOVE X DEPENDING ON THE ACCELEROMETER
MyIcare.x -= (MyIcare.x - (MyIcare.x + accX * 10))*0.6;
//MOVE HEAD TO THE LEFT OR TO THE RIGHT
if(accX > 0) {
MyIcare.gotoAndStop(2);
}else{
MyIcare.gotoAndStop(1);
}
// Vertical speed OF THE ICARE/ANGEL
vVelocity += vAcceleration;
if((MyIcare.y > middleScreen) && (vVelocity < 0)){
// ICARE IS GOING UP
MyIcare.y += vVelocity;
}else{
if(vVelocity > 0){
// ICARE IS GOING DOWN
MyIcare.y += vVelocity;
// TEST IF ICARE TOUCHES A CLOUD
for (var i:int=0; i< 5; i++){
tmpMc = myVect[i];
if (MyIcare.hitTestObject(tmpMc))
{
vVelocity = -20;
}
}
}else{
// THE WORLD IS GOING DOWN
// WHEN ICARE IS IN THE MIDDLE OF THE SCREEN
for (var j:int=0; j< 5; j++){
tmpMc = myVect[j];
tmpMc.y -= vVelocity;
}
liveScore += 5;
}
}
// CHECK IF THE CLOUDS ARE OUT OF THE SCREEN
if(myVect[0] != null){
for (var k:int=0; k< 5; k++){
tmpMc = myVect[k];
if(tmpMc.y > stage.stageHeight){
tmpMc.y = -5;
tmpMc.x = Math.random()*stage.stageWidth;
}
}
}
//ICARE IS OUT OF THE SCREEN
//PAUSE GAME
MyIcare.y = -300;
vVelocity = 0;
vAcceleration = 0;
// PLAY FUNNY SOUND
}
Most likely your problem is you haven't told your library object (stick) to be accessible to code.
To do that, open your library panel in FlashPro, right click your stick asset/movieClip, and choose properties.
On the Symbol Properties Window, check the Export For ActionScript box. Then enter stick as in the Class field.
Now you can instantiate a stick through code.
I would like to make the 5 'burger' objects bounce around the screen so they are harder to shoot as is the aim of my game. But, so far they are only lining up at the top of the stage so it's way too easy to play. Would I need to create 5 separate objects with 5 separate instance names etc.
This is what I have so far:
var firing:Boolean = false;
var bullet:Bullet1 = new Bullet1();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(event:KeyboardEvent):void {
switch(event.keyCode) {
case Keyboard.LEFT :
ball.x -= 10;
break;
case Keyboard.SPACE :
if (!firing) {
fire();
}
break;
case Keyboard.RIGHT :
ball.x += 10;
break;
case Keyboard.UP :
ball.y -= 10;
break;
case Keyboard.DOWN :
ball.y += 10;
break;
default :
break;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function fire() {
addChild(bullet);
firing = true;
bullet.x = ball.x;
bullet.y = ball.y - 60
;
}
addEventListener(Event.ENTER_FRAME, movestuff);
function movestuff(event:Event):void {
if (firing) {
bullet.y -= 20;
if (bullet.y < 0) {
firing = false;
removeChild(bullet);
}
}
}
var numBurger:Number = 5;
var array:Array = new Array();
for (var i:uint = 0; i<numBurger; i++) {
var burger:Burger = new Burger();
array.push(burger);
addChild(burger);
burger.x = 100 + 100*i;
burger.y = 50;
}
addEventListener(Event.ENTER_FRAME, checkCollision);
function checkCollision(event:Event)
{
for (var i:uint=0; i<array.length; i++)
{
if (array[i].hitTestObject(bullet))
{
removeChild(array[i]);
array.splice(i,1);
return;
}
}
}
Thanks for any help.
No, you would not have to create each movie clip separately if you use a loop to create randomized x and y locations for each burger. You can also use Math.random() to give a random speed and direction to each burger. In the code below these values are held in "direction_ary" array. This code creates five MovieClips of the "Burger"class, and places them at random points on the screen. The code also creates random speeds and directions for each MovieClip:
import flash.events.Event;
function find_random(max,min){
return Math.round(min+(max-min)*Math.random());
}
var ary:Array = [];
var direction_ary:Array = [];
for(var i:uint=0;i<5;i++){
ary[i]=new Burger();
ary[i].name="burger"+(i);
ary[i].x=find_random(stage.stageWidth-ary[i].width,ary[i].width);
ary[i].y=find_random(stage.stageHeight-ary[i].height,ary[i].height);
addChild(ary[i]);
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
for(var e:uint=0;e<100;e++){
if(direction_ary[i][0]==0||direction_ary[i][1]==0){
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
}else{
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME,update_burgers);
function update_burgers(e:Event){
for(var i:uint=0;i<5;i++){
if (ary[i].x>stage.stageWidth||ary[i].x<0){
direction_ary[i][0]*=-1;
}
if (ary[i].y>stage.stageHeight||ary[i].y<0){
direction_ary[i][1]*=-1;
}
ary[i].x+=direction_ary[i][0];
ary[i].y+=direction_ary[i][1];
}
}
The code is fairly self explanatory. Good luck with your project.
Cheers,
Drake Swartzy
I've been working on a Platformer for a couple of weeks now and i can't seem to get the level progression working. I'm using a basic hitTest on a box to signal the movement from frame 1(level 1) to frame 2 (level 2) but once the character hits the exit box, i get the following error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LevelProg_fla::MainTimeline/loop()
What can i do so that it moves to the next frame(level)? If it helps, my code is in a frame rather than a class. Basically, the only code that i'm using for level progression is
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
with "levelTwo" being the name of the next frame (next level). The rest of the game's code is as follows (pardon the messyness of it, I've been more focused on getting the darn thing to work :b)
import flash.events.KeyboardEvent;
import flash.events.Event;
//some variables to track the player's speed
var speedX = 0;
var speedY = 0;
player.height = 80.0;
player.width = 60.0;
//loop through all the platform objects to generate the level
var level:Array = new Array();
for (var i=0; i<numChildren; i++)
{
if (getChildAt(i) is platform)
{
level.push(getChildAt(i).getRect(this));
}
}
//make variables to store key states
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
//listen for key presses and releases
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=true;
if (k.keyCode==38) kUp=true;
if (k.keyCode==39) kRight=true;
if (k.keyCode==40) kDown=true;
}
function kU(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=false;
if (k.keyCode==38) kUp=false;
if (k.keyCode==39) kRight=false;
if (k.keyCode==40) kDown=false;
}
//Make a looping function
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
//lateral movement checks
if (kLeft)
{
speedX=-10;
}
else if (kRight)
{
speedX=10;
}
else
{
speedX*=0.5; //friction to slow player down (kinda like mario)
}
//does not stop the character
//move player based on the above
player.x+=speedX;
//animations
if (speedX > 0)
{
trace("right pressed");
//player.gotoAndPlay("walkRight");
}
if (speedX < 0)
{
trace("left pressed");
//player.gotoAndPlay("walkLeft");
}
//sidewards hit tests
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedX > 0) ////moving right collision and stuffs
{
player.x = level[i].left-player.width/2;
}
if (speedX < 0) ////moving left collision and stuffs
{
player.x = level[i].right+player.width/2;
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//vertical checks
speedY+=1;
player.y+=speedY;
var jumpable = false
//vertical hitTests
//note that it's the same as the x code but just changed like 5 things.
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedY > 0) ////moving down collision and stuffs
{
player.y = level[i].top-player.height/2;
speedY=0;
jumpable = true;
}
if (speedY < 0) ////moving up collision and stuffs
{
player.y = level[i].bottom+player.height/2;
speedY*=-0.5; //bounces off cielings
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//jumps if possible
if (kUp && jumpable)
{
speedY=-15;
}
//gravity might help}
//move player with camera function/code/script/tired
this.x=-player.x+(stage.stageWidth/2); //centers the player
this.y=-player.y+(stage.stageWidth/2); //centers the player
//Progresses the player to level 2
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
}