Moving objects in array - arrays

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);
}
}
}

Related

ReferenceError: Error #1069 Actionscript 3

So i have been stuck on this for about 2 weeks and i have no idea how to progress.
I have an array of movie clips called "_main.speederArray" and i'm trying to make it so that if they collide with each other then they are both destroyed. Here is my code in the "Speeder class" to detect collision.
private function detectionHandler():void{
//trace("array length", _main.speederArray.length);
detectionID = _main.gameCounter;
for ( var i:int = _main.speederArray.length -1; i >= 0; i--){
var speeder:Speeder = _main.speederArray[i];
if(speeder.destroyMe) continue;
if(speeder.detectionID == this.detectionID) continue;
if (boxIntersect(this, speeder)){
trace("collision");
destroyMe = true;
speeder.destroyMe = true;
}
}
}
Here is the boxIntersect function this code refers to. It's in the same class
private function boxIntersect ( speeder1:Speeder, speeder2:Speeder):Boolean{
if(speeder1.x + speeder1.distRight < speeder2.x + speeder2.distLeft) return false; //checking for overlap on X axis
if(speeder1.x + speeder1.distLeft > speeder2.x + speeder2.distRight) return false;
if(speeder1.y + speeder1.distBot < speeder2.y + speeder2.distTop) return false; // checking for overlap on Y axis
if(speeder1.y + speeder1.distTop > speeder2.y + speeder2.distBot) return false;
return true;
}
And then here is where i think the problem is. I have a class called "spawner" and this is where i was going to handle the objects being created and destroyed. Here is the code where i am trying to splice objects from the array depending on whether the destroyMe bool is set to true. At this stage i have confused the shit out of myself so any help would be greatly appreciated!
private function updateArray(e:Event):void{
for(var i:int = _main.speederArray.length - 1; i>=0; i--){
var speeder:Speeder = _main.speederArray[i];
if(speeder.destroyMe){
//trace("hello");
removeChild(speeder[i]); // take it off the stage
_main.speederArray[i] = null;
_main.speederArray.splice(i, 1); //remove it from the array
}
}
}
Now, the game runs however as soon as the 2 objects within the same array collide, i get the collision trace in the output window but straight after i get this :
ReferenceError: Error #1069: Property 1 not found on com.game.Speeder and there is no default value.
at com.game::Spawner/updateArray()
No idea what it means :(
Any help appreciated thanks guys!
The problem comes from the line
removeChild(speeder[i]); inside your update function.
Speeder has no properties that are called 1 and the 1 comes obviously from your for loop.
So, to solve this problem, you should simply call
removeChild(speeder);
speeder already is the object at the position i of your array. Putting [] behind an object is the same like accessing a property from it. essentially you were doing this:
removeChild(speeder.1);

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);
}
}

Partially working array/hitTestobject

I am trying new things with arrays and having some difficulty. I am trying to create multiple instances of 1 class and putting them into an array.
I am creating the instances like so:
public function creatingitem(e:TimerEvent)
{
amtcreated = Math.ceil(Math.random() * 4);
while (amtcreated >= 1)
{
amtcreated--;
var i:Number = Math.ceil(Math.random() * 3);
switch (i)
{
case 1 :
//Object1
objectnum = 1;
objectwei = 3;
r = new Board(objectnum,objectwei,stagw,stagh);
addChild(r);
fallingitem.push(r);
break;
case 2 :
//Object2
objectnum = 2;
objectwei = 4;
c = new Board(objectnum,objectwei,stagw,stagh);
addChild(c);
fallingitem.push(c);
break;
case 3 :
//Object3
objectnum = 3;
objectwei = 4;
l = new Board(objectnum,objectwei,stagw,stagh);
addChild(l);
fallingitem.push(l);
break;
default :
break;
}
}
}
Once these are created they check if they collide with the main ball:
public function hitcheck(e:Event)
{
for (var v:int = fallingitem.length - 1; v >= 0; v--)
{
if (ball.hitTestObject(fallingitem[v]))
{
trace(fallingitem[v]);
if (fallingitem[v] == r)
{
bonusscore += 100;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == c)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == l)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
trace(bonusscore);
}
}
}
The issue is I am seeing every item getting hit due to the trace function. Not all instances are meeting the if conditions. As an example I could have 2 "r" instances and when I hit both 1 will go through and add to the score and the other will just continue past. The trace directly following the hitTestObject shows me that both are being hit and registered but I am not sure why it does not add score.
Thank you,
You can't really have 2 r instances. When you're creating the instances, if you happen to create 2 rs, the second r = new Board... statement overwrites the reference, and the variable r is referring to the second one. Both objects still exist, but the variable can only refer to one of them, so when you perform the check, you're ignoring the object that was previously set to r but isn't any more.
To fix this, you could turn r, c and l into Arrays and whenever you create an instance, add it to the appropriate array. Then, you would perform the check using (r.indexOf(fallingitem[v]) != -1), which returns true if the object is in the array.
The other way, based on the provided code, would be to check whatever value objectnum is setting in the constructor, since you're setting that value based on whether it's in the r, c or l category. Though, that won't work if the property is private or might be changed.

AS3 remove all instances of an object?

I have a game with in AS3 with a document class and a custom class which is attached to a movieclip in my .fla. Instances of that object are made multiple times/second. I want to delete those instances when, let's say, there are 100 of them. (because of performance problems after a while) The instances are stored in an Array after they are made.
You can remove them by using this.removeChild(obj); and obj is your object from array. So what you need is to loop through array and remove them.
That will remove all objects when objects are over 100.
if(array.length > 100)
{
for(var i:int = array.length - 1; i > -1; i--)
{
stage.removeChild(array[i]);// or any other parent containing instances
array.pop();
//array[i] = null; // if you want to make them null instead of deleting from array
}
}
Tip: Negative Loop (i--) is faster in performance than Positive Loop (i++).
Tip: pop() is faster in performance than unshift().
Update:
That will remove objects only if they are over 100, resulting in only 100 last objects remain on stage.
if(array.length > 100)
{
for(var i:int = array.length - 1; i > -1; i--)
{
if(array.length > 100)
{
stage.removeChild(array[i]);// or any other parent containing instances
array.unshift();// if you want to delete oldest objects, you must use unshift(), instead of pop(), which deletes newer objects
//array[i] = null; // if you want to make them null instead of deleting from array
}
}
/****** MyClass.as *********/
public class MyClass extends Sprite{
private var myVar:int=8567;
private function myClass():void{
//blablabla
}
public class destroy():void{
myVar = null;
this.removeFromParent(true); //method of Starling framework
}
}
/******** Main.as ****************/
public var myInstance:MyClass = new Myclass();
//Oh!! i need remove this instance D:
myInstance.destroy();

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);
}
}

Resources