Stop and start a for loop in AS3? - actionscript-3

I'm pulling an xml and using a for loop to create a thumb list. This list is going to be quite long but I only 25 thumbs to be loaded at a time, so that the next 25 is only loaded when a user hits a button. I know how to set up a for loop in a function, but I can't quite figure out how to break up a loop where it would stop and start. I was thinking I would call the function each time a button is pressed and the loop would pick up where it left off with the next 25.
I thought maybe I could substite other variables into the for(); but everything I've tried breaks it. I tried pulling the var i:int = 0; out of the for so the function could set the i, but I guess I'm not clear on exactly how the for loop works.
What I'm doing:
function loadarticleHeadlines():void
{
for (var i:int = 0; i < egarticleXml.articlelist.articleitem.length(); i++)
{
vsThumb = new articleBox();
vsThumb.alpha = 0;
vsThumbLoader = new Loader();
vsThumbLoader.load(new URLRequest(egarticleXml.articlelist.articleitem[i].articlethumbnail));
articleListContainter.addChild(vsThumb);
vsThumb.articleImage.addChild(vsThumbLoader);
vsThumb.articleTitle.text = egarticleXml.articlelist.articleitem[i].articletitle;
titleAutosize(vsThumb.articleTitle);
vsThumb.x = next_x;
next_x += 260;
articlevsThumb[i] = vsThumb;
//vsThumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, showBox);
vsThumb.clickBtn.buttonMode = true;
}
}

Try this out.
var xml:Array = [];
for(var i:int=0;i<100;i++)
{
xml.push(i);
//array from 0-99
}
var xmlPosition:int = 0;
grabXML(xmlPosition);
//25
grabXML(xmlPosition);
//50
grabXML(xmlPosition);
//75
grabXML(xmlPosition);
//100
function grabXML(position:int):void
{
for(position;position<xml.length;position++)
{
trace(xml[position]);
//yields 0-24, 25-49, 50-74, and 75-99
if(position === xmlPosition + 25)
{
break;
}
}
xmlPosition += 25;
}
I'm breaking as soon as the parameter is 25 more than its original value (xmlPosition). Calling the function additional times will yield nothing, as xmlPosition is greater than xml's length property.

Related

Actionscript: How can I create a counter that registers a hitTestObject and shows the score on the main stage?

My game counts the number of hits to an object and brings the user either to a winning or losing page. How can my hitTestObject count the number of hits while showing the number on the main stage? If the user hits "friend" 5 times, I want it to play the "youWin" layer and if they hit a "biter" once, I want it to play the "youLose" layer. (Please help this is for my final project and I'm almost done) Thank you! :)
stop();
addEventListener(Event.ENTER_FRAME,fishHit);
function fishHit(e:Event){
if (theFish.hitTestObject(biter)){
removeEventListener(Event.ENTER_FRAME,fishHit);
gotoAndPlay("youLose");
}
}
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter:shark=new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
}
for (var what=0; what<5; what++){
var friend:starfish=new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
}
var counter : int = 0;
addEventListener(Event.ENTER_FRAME,winner);
function winner (e:Event){
if(theFish.hitTestObject(friend)) {
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5)
removeEventListener(Event.ENTER_FRAME,winner);
gotoAndPlay("youWin");
}
}
You need many updates in your code, but I'll try to copy and paste your code with small modifications. You should define your variables outside of for loop, also you must add multiple objects like 'friends' to an array.
stop();
// arrays
var friends:Array = new Array();
var biters:Array = new Array();
var counter : int = 0;
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter = new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
// push it to the array
biters.push(biter)
}
for (var what=0; what<5; what++){
var friend = new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
// push it to the array
friends.push(friend)
}
addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event){
// theFish vs biters
for (var i:int = 0; i < biters.length; i++){
if (theFish.hitTestObject(biters[i])){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youLose");
}
}
// theFish and friends
for (i = 0; i < friends.length; i++){
if(theFish.hitTestObject(friends[i])) {
// remove this friend so it does not increase counter
friends.splice(i,1);
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youWin");
}
}
}
}

AS3 Add Child at the position of another Child

Hey I have got some cavemen that when they build huts I want the huts to be added at the coords of the caveman I last clicked on which requires the ability to know exactly what caveman the user clicked on/tapped. Here is the code for spawning in the cavemen:
//////////////////////
///Starting Cavemen///
//////////////////////
var cavemanVar:Array = new Array(50);
for (var i:Number = 0; i < 50; i++)
{
cavemanVar[i] = 0;
}
var foo:MovieClip = new btn_caveman();
cavemanVar[0] = addChildAt(foo, 7);
var bar:MovieClip = new btn_caveman();
cavemanVar[1] = addChildAt(bar, 7);
cavemanVar[0].x = 335.50;
cavemanVar[0].y = 316.55;
cavemanVar[1].x = 335.50;
cavemanVar[1].y = 369.5;
stage.addEventListener(Event.ENTER_FRAME, example2);
function example2 (evt:Event) {
for (i = 0; i < 50; i++)
{
if (cavemanVar[i] != 0)
{
cavemanVar[i].addEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenu3);
}
}
}
function option1CavemenSpawn():void {
trace("using option 1")
actions += 1;
score += 5;
remaningActions += 1;
updateTextBox();
var foo6:MovieClip = new btn_caveman();
cavemanVar[2] = addChildAt(foo6, 7);
cavemanVar[2].x = 352.10;
cavemanVar[2].y = 260.80 + Math.random() * (392.40 - 260.80);
}
Any help would be great, I have tried using 'cavemanVar', 'cavemanVar[2]', 'cavemanVar[i]' and nothing is what I want it to be.
Hope I explained it properly it's a tricky thing to explain. I also have a move caveman feature I want to implement which would select the last clicked/tapped caveman and move it where the user clicks/taps so can any of this be done and if so how?
EDIT:
function btn_cavemanMenu3(event:TouchEvent):void {
btn_cavemanM.gotoAndStop(2);
trace('2');
allowBuildHut();
cancelTapCaveman();
allowTapCavemanClose();
if (remaningActions <= 2 || stone <= 29) {
cancelBuildHut();
}
}
Do you mean something like,
cavemanVar[i].addEventListener(TouchEvent.TOUCH_TAP, onTap);
function onTap(e:TouchEvent):void {
var caveman:btn_caveman = e.currentTarget as btn_caveman;
trace("caveman tapped --- (" + caveman.x + ", " + caveman.y + ")");
}
Okay, some things I noticed right away:
Attaching eventListeners with each frame, again and again. This will make your game slow if you make your game bigger. I'm not sure, but I think multiple event listeners with the same arguments don't stack, so it's not THAT bad.
Missing a return type for example2.
But aside from that, I think the reason that what you're trying to do doesn't work is because you're not referencing the selected caveman in your btn_cavemanMenu3 function. Via event.currentTarget you can reference the tapped caveman.
Currently, your question name and your question description conflict. What exactly do you wish to achieve? What is working and what isn't working right now?

AS3-Having a mouse click affect object in an array's timeline

I'm going crazy with this. I have a few bears on the stage and have listed them in an array. I want them to change their animation frame when clicked as long as they are not on the "down" animation frame to begin with. Below is the code. The problem occurs below the //check if they get hit line.
//put the bears in an array
var bearsArray: Array = new Array();
for (var i=0; i<numChildren;i++) {
if (getChildAt (i) is bear_mc) {
bearsArray.push(getChildAt(i));
}
}
//move them up and down
addEventListener(Event.ENTER_FRAME,upAndDown);
function upAndDown(event:Event){
if (Math.random() < 0.02){
var randomBear = Math.floor(Math.random() * 9);
bearsArray[randomBear].gotoAndPlay("popup");
}
}
//check if they get hit
for (var j:int = 0; j < bearsArray.length; j++){
bearsArray[j].addEventListener(MouseEvent.CLICK, hitBears);
}
function hitBears(e:MouseEvent){
for (var k: int=0; k<numChildren; k++){
if (bearsArray[k].currentFrame != "down"){
trace("clicked");
bearsArray[k].gotoAndPlay("surprised");
}
}
}
currentFrame returns an integer, not string. If you want to use string, you have to use currentFrameLabel or currentLabel.
EDIT: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/MovieClip.html#currentLabel
If you want to control only one bear, remember that you don't need to cycle through them (actually that would serve no purpose as you would be checking every one of them). The better (and correct) approach would be this:
function hitBears(e:MouseEvent){
var bear:MovieClip = e.currentTarget as MovieClip;
if(bear.currentLabel != "down") { //or currentFrameLabel, depends how your mc is set up
trace("clicked");
bear.gotoAndPlay("surprised");
}
}
I got it working by checking a hittest with the mouse instead of just checking the click. That works for some reason.

Trying to remove object throws error 1009 cannot access a property or method of null object reference

Working on a flash game, in a previous game I had enemies come in by using an array and when they were killed or moved off the stage I would just remove them from the array. For some reason when I use exactly the same code in this game, it throws a 1009: error when I try to remove the array object, basically saying that there's nothing there. . . Which is strange.
Here's the code:
public function addZombie()
{
var zom:Zombie = new Zombie();
zom.y = 20;
zom.x = Math.floor(Math.random()*(1 + 500 - 30)) + 30;
addChild(zom);
zombies.push(zom);
numZombies++;
}
That's the function where it's added in, zombies is the array and it's pushed into the array in this function. Here's the code where I'm attempting to remove it:
for (var i:int = 0; i < zombies.length; i++)
{
if (zombies[i].y + zombies[i].height / 2 > 400) {
removeChild(zombies[i]);
zombies.splice(i,1);
numZombies--;
addZombie();
}
}
removeChild(zombies[i]); <-- This is the part that throws the error when it attempts to remove it. It removes some of them strangely enough, but not all of them.
I don't believe the loop is doing quite what you expect it to. When you remove an element from an array in this way, all the elements after the removed elements are moved down. So, if you have code like:
var testArr:Array = new Array();
testArr.push('First');
testArr.push('Second');
testArr.push('Third');
testArr.push('Fourth');
for (var i:int = 0; i < testArr.length; i++) {
testArr.splice(i,1);
}
The results of the loop will be:
i=0, testArr = ['Second', 'Third', 'Fourth']
i=1, testArr = ['Second', 'Fourth']
i=2 END OF LOOP
It would probably be better to use a while loop, incrementing the index only if the element is not removed (since removing the element moves a new element to that index position).
I don't see why you're getting the null object reference, but this would be causing other problems (why some are removed but not all).
The explanations of Bill Turner are the correct ones, but as it didn't seem to help you fix your issue, you might want to try this:
var zombieCount:int = zombies.length;
for (var i:int = 0; i < zombies.length; i++)
{
var zombie = zombies[i];
if (zombie.y + (zombie.height / 2) > 400) {
removeChild(zombie);
zombies.splice(i,1);
i--; // So that the loop will pass with the same value next time
numZombies--;
}
}
for (var j:int = zombies.length; j < zombieCount; j++)
{
addZombie();
}

How to compare properties of objects inside a vector?

I have a couple of display objects moving around the screen, the all belong to the same Vector.
I would like to create a function that lets me pick an object with the lowest x value at the moment the function is called.
This is quite easy and if you're into programming, you should be able to do it yourself, but if you're a beginner, I'll give you some code:
var vec:Vector.<DisplayObject> = new Vector.<DisplayObject>();
function getLowestXObject():DisplayObject
{
var minX:DisplayObject = vec[0];
for(var i:int = 1; i < vec.length; i++)
{
if(minX.x > vec[i].x)
{
minX = vec[i];
}
}
return minX;
}