Trouble with array order - arrays

I have a couple of if statements within a timer function, checking if the enemy's hp is 0. The enemies are added into an array. When one enemy hp hits 0, they are taken from the array and removed. When the array length is 0, the game goes to the next level. For some reason, when the first enemy's hp reaches 0, then it automatically goes to the next level without even checking the other enemy's hp. It worked on the first level, where I only had 1 enemy, but the second level, I have two enemies. I would have to defeat the second enemy, then the first in order for it to go to the next level. I think it may have something to do with the first enemy being the first in the array. Any ideas on how I can change the code to make it disregard the order in which enemy is defeated first?
public var enemy:Enemy = new Enemy();
public var enemy2:Enemy = new Enemy();
public var enemyArray:Array = [];
Level Timer(Timer that sets up the level, runs once):
if (level.levelNumber == 1)
{
enemyArray.push(enemy);
addChild(player);
addChild(enemy)
enemy.enemyMoveTimer.start();
enemy.enemyAttackTimer.start();
onGameTimer.start();
}
if (level.levelNumber == 2)
{
enemyArray.push(enemy, enemy2);
addChild(player);
addChild(enemy)
addChild(enemy2)
enemy.enemyMoveTimer.start();
enemy.enemyAttackTimer.start();
enemy2.enemyMoveTimer.start();
enemy2.enemyAttackTimer.start();
onGameTimer.start();
}
Game timer(timer that checks the enemy lives, keeps running):
if (enemyArray.length == 0)
{
trace("NEXT LEVEL");
removeChild(player);//remove player from the current level
onLevelTimer.removeEventListener(TimerEvent.TIMER, timerLevel);
levelNumber += 1;
onLevelTimer.addEventListener(TimerEvent.TIMER, timerLevel);
onGameTimer.stop();
}
if (enemy.enemyHP <= 0)
{
enemy.enemyHP = 0;
enemy.enemyMoveTimer.stop();
enemy.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(0,1);
try
{
removeChild(enemy)
}
catch (e:ArgumentError){
}
}
if (enemy2.enemyHP <= 0)
{
enemy2.enemyHP = 0;
enemy2.enemyMoveTimer.stop();
enemy2.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(1,1);
try
{
removeChild(enemy2)
}
catch (e:ArgumentError) {
}
}

There's more code there that could be the cause of the issue, so I'm just going to assume that it looks something like what I've written below. It also dispenses with multiple if statements, in favor of simply iterating over your enemyArray, checking each as you wanted to (behold the power of loops!).
var enemyMoveTimer:Timer = new Timer(1000, 0);
enemyMoveTimer.addEventListener(TimerEvent.TIMER, enemyTimerListener);
enemyMoveTimer.start();
var enemyArray:Array = [new Enemy("enemy1"), new Enemy("enemy2")];
function enemyTimerListener(e:Event):void {
for (var i:String in enemyArray) {
var enemy:Enemy = enemyArray[int(i)];
if (enemy.enemyHP <= 0) {
enemy.enemyMoveTimer.stop();
enemy.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(int(i),1);
if (enemy.parent != null) {
removeChild(enemy);
}
}
}
}
What isn't shown is how you're detecting and advancing to "the next level". How are these enemies being added to the array? Since it seems you've rolled your own Enemy class, what's that class look like? Why are you using try ... catch?
In any case, if the above works, fun; otherwise, we'll need more code to know what's going on.

Related

HitTest Object Bug when 2 object from same array hit

Hey guys so I ran into a Bug with my code I have a Movie Clip Object called mainFish that is setup with the array aFishArray and I have the array setup in a for loop to check a HitTest with playerHook. Now everything works completely fine but the issue that I am having is when say two of the Fish hit the hook at the same time one of of the fish hooks on the hook and the other just stays on the screen and i run into my sound Object repeating over again and other errors. Here is my functions that I use to track the fish:
Here is my functions inside the ENTER_FRAME Game Loop:
//Check if fish is null then run function
if (mainFish == null)
{
checkPlayerHitFish();
}else
{
trackFish();
}
and the functions:
private function checkPlayerHitFish():void
{
//loop through all our fishes
for (var j:int = 0; j < aFishArray.length; j++)
{
//get current fish in j loop
var currentFish:mcMainFish = aFishArray[j];
//test if current fish is hitting current playerhook
if (currentFish.hitTestObject(playerHook))
{
//trace("hit initialized");
mainFish = currentFish;
//Stop the fish from moving
currentFish.stopFish();
//fishing reel sound
fishingReelSoundChannel;
fishReelSound = new fishingReel();
fishingReelSoundChannel = fishReelSound.play(0, 9999);
fishingReelBoolean = true;
}
}
}
and the trackFish Function:
private function trackFish():void
{
mainFish.x = playerHook.x;
mainFish.y = playerHook.y + 15;
}
Can anyone see if I am doing anything wrong or how to go about fixing this issue?
The problem is that while you're only allowing one fish to be moved by the hook, you're still checking for hits for all the fish. This both stops them, and creates a new sound file.
The way to avoid this is to stop checking for fish collisions after a fish has already been hooked. To do this you can break out of the loop once you hook a fish:
private function checkPlayerHitFish():void
{
//loop through all our fishes
for (var j:int = 0; j < aFishArray.length; j++)
{
//get current fish in j loop
var currentFish:mcMainFish = aFishArray[j];
//test if current fish is hitting current playerhook
if (currentFish.hitTestObject(playerHook))
{
//trace("hit initialized");
mainFish = currentFish;
//Stop the fish from moving
currentFish.stopFish();
//fishing reel sound
fishingReelSoundChannel;
fishReelSound = new fishingReel();
fishingReelSoundChannel = fishReelSound.play(0, 9999);
fishingReelBoolean = true;
//break out of the loop
break;
}
}
}
Notice the break near the bottom. This will cause you to "break" out of the loop, preventing any further iterations. That way it will stop checking for collisions after the first successful hit test, and only react to one fish.

Array throwing exception

I can't seem to put my finger on this and why the array is not being initialized.
Basically I am coding a 2d top down spaceship game and the ship is going to be fully customizable. The ship has several allocated slots for certain "Modules" (ie weapons, electronic systems) and these are stored in an array as follows:
protected Array<Weapon> weaponMount;
Upon creating the ship none of the module arrays are initialized, since some ships might have 1 weapon slot, while others have 4.
So when I code new ships, like this example:
public RookieShip(World world, Vector2 position) {
this.width = 35;
this.height = 15;
// Setup ships model
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
chassis.setAsBox(width / GameScreen.WORLD_TO_BOX_WIDTH, height / GameScreen.WORLD_TO_BOX_HEIGHT);
fixtureDef.shape = chassis;
fixtureDef.friction = 0.225f;
fixtureDef.density = 0.85f;
fixture = body.createFixture(fixtureDef);
sprite = new Sprite(new Texture(Gdx.files.internal("img/TestShip.png")));
body.setUserData(sprite);
chassis.dispose();
// Ship module properties
setShipName("Rookie Ship");
setCpu(50);
setPower(25);
setFuel(500);
setWeaponMounts(2, world);
setDefenseSlots(1);
addModule(new BasicEngine(), this);
addModule(new BasicBlaster(), this);
// Add hp
setHullHP(50);
setArmorHP(125);
setShieldHP(125);
}
#Override
public void addModule(Module module, Ship currentShip) {
// TODO Auto-generated method stub
super.addModule(module, currentShip);
}
#Override
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
// super.setWeaponMounts(weaponMounts, world);
}
#Override
public String displayInfo() {
String info = "Everyones first ship, sturdy, reliable and only a little bit shit";
return info;
}
When I set the number of weapon mounts the following method is called:
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
}
This basically initializes the array with a size (weapon mounts available) to whatever the argument is. Now to me this seems fine but I have setup a hotkey to output the size of the Array, which reports zero. If I try to reference any objects in the array, it throws an outofbounds exception.
The addModule method adds to the array as follows:
public void addModule(Module module, Ship currentShip) {
currentShip.cpu -= module.getCpuUsage();
currentShip.power -= module.getPowerUsage();
if(module instanceof Engine){
engine = (Engine) module;
}else if(module instanceof Weapon){
if(maxWeaponMounts == weaponMount.size){
System.out.println("No more room for weapons!");
}else{
maxWeaponMounts += 1;
weaponMount.add((Weapon)module);
}
}
}
My coding ain't great but heh, better than what I was 2 month ago....
Any ideas?
First of all, You should avoid instanceof. It's not a really big deal performance-wise, but it always points to problems with your general architecture. Implement two different addModule methods. One that takes a Weapon, and one that takes an Engine.
Now back to topic:
else if(module instanceof Weapon){
if (maxWeaponMounts == weaponMount.size) {
System.out.println("No more room for weapons!");
} else{
maxWeaponMounts += 1;
weaponMount.add((Weapon)module);
}
}
It looks like you use maxWeaponMounts as a counter instead of a limit. That's why I assume that it will initially be 0. The same holds for Array.size. It is not the limit, but size also counts how many elements the Array currently holds. Thus you will always have (maxWeaponMounts == weaponMount.size) as 0 == 0 and you will not add the weapon to the array. It will always stay empty and trying to reference any index will end in an OutOfBoundsException.
What you should actually do is using maxWeaponMounts as a fixed limit and not the counter.
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
maxWeaponMounts = weaponMounts;
}
else if(module instanceof Weapon){
if (weaponMount.size >= maxWeaponMounts) {
System.out.println("No more room for weapons!");
} else{
weaponMount.add((Weapon)module);
}
}

#1023 StackOverflow ERROR

I have problem with this array thing I am doing. U can just plug in the code and run.
I need to have 2 things display out of the same array and which ever is picked gets kickedout from the array and stashed into another one.
One of the 2 things that are displaying out is picked at random and the other one goes in order it was put in.
So the logic I applied, or tried applying and is not working very well is..
Once the 2 things display out and if u pick the index count, no numbers change since the index count becomes subtracted by one, so the object after it gets pushed up.
but if the random choice is picked the index count moves up by one since it needs to keep moving...
The error i get is this:
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at Level3Torture_fla::MainTimeline/civilizedorder()[Level3Torture_fla.MainTimeline::frame1:87]
at Level3Torture_fla::MainTimeline/goNext()[Level3Torture_fla.MainTimeline::frame1:114]
at Level3Torture_fla::MainTimeline/switchpic()[Level3Torture_fla.MainTimeline::frame1:79]
This is the Code:
import flash.sampler.NewObjectSample;
import flash.display.Sprite;
import flash.events.MouseEvent;
var eating_breakfast:Sprite;
var walking:Sprite;
var swimming:Sprite;
var art:Sprite;
var choices:Array = new Array ();
//Sprite Creation
eating_breakfast = new Sprite ();
eating_breakfast.graphics.beginFill(0xE39D43);
eating_breakfast.graphics.drawRect(0,0,50,50);
eating_breakfast.graphics.endFill();
eating_breakfast.x = 50;
eating_breakfast.y = 50;
walking = new Sprite ();
walking.graphics.beginFill(0xC3266C);
walking.graphics.drawRect(0,0,50,50);
walking.graphics.endFill();
walking.x = 100;
walking.y = 100;
swimming = new Sprite ();
swimming.graphics.beginFill(0x48AFD1);
swimming.graphics.drawRect(0,0,50,50);
swimming.graphics.endFill();
swimming.x = 150;
swimming.y = 150;
art = new Sprite ();
art.graphics.beginFill(0xafdb44);
art.graphics.drawRect(0,0,50,50);
art.graphics.endFill();
art.x = 200;
art.y = 200;
//adding sprites into array
choices.push( eating_breakfast);
choices.push(walking);
choices.push(swimming);
choices.push(art);
var indexcount = 0;
var randomize:Number;
var storageArray: Array = new Array ();
civilizedorder();
randomizedorder();
this.addEventListener(MouseEvent.CLICK,switchpic);
//pick the target generated object
function switchpic(t:MouseEvent)
{
//for index count
if (t.target == choices[indexcount])
{
storageArray.push(choices[indexcount]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(indexcount,1);
goNext();
};
// for randomize
if (t.target == choices[randomize])
{
storageArray.push(choices[randomize]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(randomize,1);
indexcount++;
trace("The Index count is" + indexcount);
goNext();
}
}
//generates the index count object
function civilizedorder()
{
addChild(choices [indexcount]);
choices[indexcount].x = 300;
}
trace("The number of choices in the choice array is " + choices.length);
//generates the randomized object
function randomizedorder()
{
randomize = Math.floor(Math.random() * choices.length);
trace("the random number is" + randomize);
if (randomize == indexcount )
{
randomizedorder();
}
else
{
addChild(choices [randomize]);
}
}
//EDIT
function goNext()
{
trace("The storagearray has " + (storageArray.length));
if (choices.length < 0 || choices.length > 0)
{
if (indexcount > choices.length-1)
{
indexcount = choices.length - 1;
}
civilizedorder();
randomizedorder();
}
}
It is giving me a new error now. It's called StackOverflow. I am not entirely sure what is going wrong now.
EDIT: To add a conditional and check if you will be out of bounds for adding a child in this array, try this:
if(indexcount <= choices.length){
addChild(choices [indexcount]);
}
Try commenting out the splicing in the switchpic() method. That or re-add those values/sprite instances to the array.
I think that you've sliced from the "choices" array twice in the switchpic() method, and never actually add to the array ever again. So you'll eventually end up with an empty choices array. Hence the error.
In the second conditional, if (t.target == choices[randomize]), you increment indexcount, and then call goNext() which regenerates the randomize value to not equal the indexcount, but also tries to re-add a child sprite.
This could cause an array of 4 items to become 2 items, and then, possibly, randomize = 0, indexcount = 1. In the second pass, you might have an array of 0 items, with randomize = 0, indexcount = 1 and the error to occur.
Here's the flow, I imagine:
It looks like you're clicking on an instance of a sprite.
Then it calls switchpic(), which executes:
...
choices.splice(indexcount,1);
...
and then goNext()
which calls civilizedorder()
which executes:
...
addChild(choices [indexcount]);
...
you should check indexcount is never outside of 0-3 range.
in function goNext(), change the code as follows:
function goNext()
{
trace("The storagearray has " + (storageArray.length));
if(choices.length <> 0)
{
if(indexcount > choices.length-1)
indexcount = choices.length-1;
civilizedorder();
randomizedorder();
}
}

Select random elements from an array without repeats?

edit: I can't believe I didn't catch this sooner. Turns out my problem was re-declaring my first variables over and over again, essentially starting the program fresh instead of continuing it. To fix it, I replaced the first two lines with this:
if (initialized === undefined) {
trace("INITIALIZING");
var MCs = [];
var lastPos = "intializer";
var initialized = 1;
}
Now it works like a charm. I feel like a noob for this one; sorry to anyone whose time I wasted. I'd post this as an answer to my own question, but it won't let me since I'm still new.
Original Post follows:
I'm trying to make a flash that will randomly choose an ad, play it, and then randomly play another. To that end, I've succeeded by shuffling an array, and then gotoAndPlay-ing the label in the first element of the array, and then removing that element. At the end of each ad is gotoAndPlay(1); with all the main code being on the first frame. If the array is empty, it rebuilds it and reshuffles it.
The problem is, I don't want it to repeat any ads until its run through all of them; I think I've got that down, but I'm not positive. Further, I don't want the last element in the array to be the same as the first in the new one, so the same ad won't ever show twice in a row. I'm trying to have it detect if the element it just used matches the one it's about to use, and reshuffle if that happens, but in my testing it continues to occasionally show the same ad twice in a row.
I'm obviously doing something wrong, but being entirely new to ActionScript3 (and in fact to flash) I'm having a lot of trouble identifying what it is. Here's what I have right now:
var MCs = [];
var lastPos = "intializer";
if (MCs.length == 0) {
MCs = reset();
if (lastPos == MCs[0]) {
while (lastPos == MCs[0]) {
MCs = reset();
}
}
}
if (MCs.length > 0) {
lastPos = MCs[0];
MCs.splice(0,1);
gotoAndPlay(lastPos+"MC");
}
function reset(){
var PrepMCs = new Array("Image1", "Image2", "Image3");
var WorkMCs = new Array(PrepMCs.length);
var randomPos:Number = 0;
for (var i:int = 0; i < WorkMCs.length; i++)
{
randomPos = int(Math.random() * PrepMCs.length);
WorkMCs[i] = PrepMCs.splice(randomPos, 1)[0];
}
return WorkMCs;
}
Personally, I'd rather just do this with JavaScript, HTML, and images; it'd be really simple. But for hosting/CMS reasons I don't have any control over, I'm limited to a single file or a single block of code; I can't host anything externally, which as far as I can tell leaves Flash as my best option for this.
Any help would be greatly appreciated, thanks! If I've done something horribly, horribly wrong, and it's a wonder this even runs at all, don't hesitate to tell me!
edit: It just occurred to me, it is perfectly fine if the second run is in the same order as the first run, etc. The main thing is, it needs to be random. This is probably much easier to implement.
edit 2: MASSIVE DERP HERE. Every time it runs, it re-initializes MCs and lastPos... in other words, it's shuffling every time and starting over. What I should be researching is how to only run a line of code if a variable hasn't been initialized yet.
Blatantly stealing from #32bitKid, this is my version.
The main problem I have with his solution is the push/splice idea. As much as possible, I like to create once, and reuse. Shrinking and growing arrays is bulky, even if effective.
Also, this method does not re-order the array, which may or may not be valuable.
BTW, I like the way that he prevents a repeat of the previous item ("almost empty").
So here is another method:
package
{
public class RandomizedList
{
private var _items:Array;
private var idxs:Array;
private var rnd:int;
private var priorItemIdx:int;
private var curIdx:int;
public function RandomizedList(inarr:Array)
{
items = inarr;
}
private function initRandomize():void
{
idxs = new Array();
//Fisher-Yates initialization (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle):
idxs[i] = 0;
for (var i:int = 1; i < items.length; i++)
{
rnd = int(Math.random() * (i + 1));
idxs[i] = idxs[rnd];
idxs[rnd] = rnd;
}
curIdx = 0;
priorItemIdx = -1;
}
private function randomize():void
{
var tempint:int;
//Fisher-Yates (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle):
for (var i:int = items.length; i >= 1; i--)
{
rnd = int(Math.random() * (i + 1));
tempint = idxs[i];
idxs[i] = idxs[rnd];
idxs[rnd] = tempint;
}
curIdx = 0;
}
public function next():void
{
if (curIdx >= idxs.length)
{
randomize();
}
if (items.length > 1 && priorItemIdx == idxs[curIdx])
{
curIdx++;
}
priorItemIdx = idxs[curIdx++];
return items[priorItemIdx];
}
public function get items():Array
{
return _items;
}
public function set items(value:Array):void
{
_items = value;
initRandomize();
}
}
}
I would use a utility class like this to abstract out the behavior I wanted:
import flash.text.TextField;
class Randomizer {
private var unused:Array = [];
private var used:Array;
public function Randomizer(playList:Array) {
used = playList;
}
public function next():* {
// If almost empty, refill the unused array
if(unused.length <= 1) refill();
// Get the first item off the playList
var item:* = unused.shift();
// Shove it into the bucket
used.push(item);
// return it back
return item;
}
public function refill():void {
var i:int;
// Fisher-Yates shuffle to refill the unused array
while(used.length > 0) {
i = Math.floor(Math.random() * used.length)
unused.push(used.splice(i,1)[0])
}
}
}
Notice that it refills the unused array when the unused array still has one item in it, this makes it impossible for the last result to repeat twice in a row. This will return each item once before before looping, and will never repeat the same item twice.
You would use it by saying something like:
var ads:Randomizer = new Randomizer(["Image1", "Image2", "Image3"]);
ads.next(); // will return something
ads.next(); // will return something
ads.next(); // will return something
ads.next(); // will return something
// Keep going into infinity...
There is a little test example of this code working here.
See if this makes any sense
//create your array of all your ad names/frame labels
var PrepMCs:Array = new Array("Image1", "Image2", "Image3");
var shuffledMCs:Array = [];
//store the name of the last played ad in this var
var lastAdPlayed:String;
//shuffle the array
shuffleArray(PrepMCs);
function shuffleArray(arrayToShuffle:Array):void {
//clear the array
shuffledMCs = [];
var len:int = arrayToShuffle.length;
for(var i:int = 0; i<len; i++) {
shuffledMCs[i] = arrayToShuffle.splice(int(Math.random() * (len - i)), 1)[0];
}
//test to see if the new first ad is the same as the last played ad
if (lastAdPlayed == shuffledMCs[0]) {
//reshuffle
shuffleArray(PrepMCs);
} else {
lastAdPlayed = [0];
trace(shuffledMCs);
playAds();
}
}
//after each ad has played, call this function
function playAds():void {
if (shuffledMCs.length > 0) {
gotoAndPlay(shuffledMCs[0]);
shuffledMCs.splice(0,1);
} else {
//array is empty so we have played all the ads
shuffleArray(PrepMCs);
}
}

Moving objects in array

I have an array which is filled with platforms that are supposed to move.
var MovingPlatformArray:Array = new Array();
for (var c:int = numChildren - 1; c >= 0; c--){
var child3:DisplayObject = getChildAt(c);
if (child3.name == "movingplatform"){
MovingPlatformArray.push(child3);
}
}
this.addEventListener(Event.ENTER_FRAME,ctrl_birdie);
function ctrl_birdie(e:Event):void{
for(var c in MovingPlatformArray){
MovingPlatform[c].y += speed;
if(MovingPlatformArray[c].hitTestPoint(birdie.x,birdie.y,true)){
birdtelleryvertrager=0;
birdtellery = 0;
birdie.y-=14;
}
if(movingplatform.y <= 25){
speed = 2;
}
if(movingplatform.y >= 350){
speed = -2;
}
}
Right now I have 2 moving platforms in this array. But only one moves up and down. But they both register a touch with the birdie. Am I doing something wrong?
In your listener, you're only setting the position of one platform, which ever one "movingplatform" is a reference to. As all your stage instances of moving platforms are named "movingplatform", one lucky platform is getting referenced by name (the rest ignored), instead of what you intended, which is to use the references in your array and adjust each platform.
You probably meant for movingplatform to be a local variable in your event handler, declared something like this:
var movingplatform:DisplayObject = MovingPlatformArray[c] as DisplayObject;
I'd recommend using a for each loop in place of the for in, because I think it's a little cleaner, but this is a minor style thing:
for each (var platform:DisplayObject in MovingPlatformArray)
{
platform.y += speed;
... rest of your code ...
}
For the sake of clarity, I edited the loop variable to be platform instead of movingplatform, to avoid confusion of having a local variable shadow a stage instance (i.e. this.movingplatform). I wanted it to be clear that the stage instance name is not being used here, because the unintentional instance name reference in your code is the source of your problem in the first place.
As far as i'm concerned, you have two options. use a for each, as adam smith suggested or use a for-loop as it was intended to be used :)
for(var c:uint = 0; c < MovingPlatformArray.length; c++){...
and btw: should "MovingPlatform[c].y += speed;" not be "MovingPlatformArray[c].y += speed;"?
edit: looking at your code, i would also suggest you use MovingPlatformArray[c].hitTestObject(birdie) instead of MovingPlatformArray[c].hitTestPoint(birdie.x,birdie.y,true)
If I were you, I would bring the logic for the platform out, and store it in a class. (Ideally you would do this for the birdie object as well). I have created an example below. The movieclips on the stage should extend Platform rather than MovieClip so they invoke the methods at the bottom.
// Use vectors if you know all the items are going to be the same type
var platforms:Vector.<Platform> = new <Platform>[];
for (var c:int = numChildren - 1; c >= 0; c--){
var child:DisplayObject = getChildAt(c);
// You shouldn't check against names (as per the original post). Because
// names should be unique
if (child is Platform){
platforms.push(child);
// This could be random so each platform has a different range
// This means platform 1 could go from y 30 to y 400, platform 2
// could go from y 60 to y 200, etc
child.setRange(25, 400);
}
}
this.addEventListener(Event.ENTER_FRAME, gameLoop);
// Have an overall game loop
function gameLoop(e:Event):void {
// Loop over the platforms
platforms.forEach(function(item:Platform, i:int, a:Vector.<Platform>):void {
// Hit test function in the class means you only have to pass in one mc
// rather than the points and a boolean
if(item.hitTest(birdie)) {
birdtelleryvertrager=0;
birdtellery = 0;
birdie.y-=14;
}
// Removed the movement logic, this should be kept out of the game loop
// plus how much better does this read?
item.move();
});
}
Then in a class location somewhere, like in a folder game/activeObjects
// A class for the platform stored else where
package game.activeObjects
{
import flash.display.MovieClip;
/**
*
*/
public class Platform extends MovieClip {
private const SPEED:Number = 2;
private var _direction:int = 1;
private var _minimumHeight:Number = 25;
private var _maximumHeight:Number = 350;
public function Platform() {
}
public function setRange(minimumHeight:Number, maximumHeight:Number) {
_minimumHeight = minimumHeight;
_maximumHeight = maximumHeight;
}
public function move():void {
this.y += SPEED * _direction;
if(this.y <= _minimumHeight) {
_direction = 1;
} else if(this.y >= _maximumHeight) {
_direction = -1;
}
}
public function hitTest(mc:MovieClip):Boolean {
return hitTestPoint(mc.x,mc.y,true);
}
}
}

Resources