How to create a hierarchy Menu/Icon - actionscript-3

I dont know if the question represent exactly what i want to ask, but i could`t figure how else to name what i want to do.
So im trying to create a 3x3 grid and in every cell i have a image.
I can click on any of the 2nd cell of a column only if the 1st of the same column has been clicked before that.What i mean is
i can click cell No:5 only if 4 has been clicked before that
i can click cell No:9 only if 8 and 7 has been clicked before that
i can click cell No:1,4,7 anytime.
and also when they are clicked their alpha gets to 0.1 (so i know that the cell has been clicked.)
currently i the logic for creating the grid and changing the alpha of any object i click but i don`t have the logic for the hierarchy.
public function Main()
{
var index:int = 0
var col:int = 3
var row:int = 3
for (var i:int = 0; i < row; i++)
{
for (var j:int = 0; j < col; j++)
{
var cls:Class = Class(getDefinitionByName("Bitmap" + (index + 1) ));
myImage = new Bitmap( new cls() );
var myImage_mc:MovieClip = new MovieClip();
myImage_mc.addChild(myImage)
myImage_mc.x = 100 + i * (myImage_mc.width + 10)
myImage_mc.y = 100 + j * (myImage_mc.height + 10)
this.addChild(myImage_mc);
myImage_mc.mouseEnabled = true
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
index++
}
}
}
private function onClick(ev:MouseEvent):void
{
trace(ev.target.name)
ev.currentTarget.alpha = 0.1;
}

Another way is to use a link variable to link element.
public class BitmapButton extends Sprite {
public var next:BitmapButton = null;
}
public class Main extends Sprite {
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var index:int = 0
var col:int = 3
var row:int = 3
for (var j:int = 0; j < col; j++)
{
var lastRowElement:BitmapButton = null;
for (var i:int = 0; i < row; i++)
{
var bmpd:BitmapData = new BitmapData( 100, 100, false, Math.floor( 0xff + Math.random() * 0xffffff ) );
var myImage:Bitmap = new Bitmap( bmpd );
var myImage_mc:BitmapButton = new BitmapButton();
myImage_mc.addChild(myImage)
myImage_mc.x = 100 + j * (myImage_mc.width + 10);
myImage_mc.y = 100 + i * (myImage_mc.height + 10);
myImage_mc.name = i + "_" + j;
this.addChild(myImage_mc);
myImage_mc.mouseChildren = false;
myImage_mc.mouseEnabled = false;
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
if ( lastRowElement == null ) {
myImage_mc.mouseEnabled = true;
} else {
lastRowElement.next = myImage_mc;
}
lastRowElement = myImage_mc;
index++
}
}
}
private function onClick(ev:MouseEvent):void
{
trace(ev.target.name)
if ( ev.target is BitmapButton ) {
var btn:BitmapButton = ev.target as BitmapButton;
ev.currentTarget.alpha = 0.1;
if( btn.next != null ) {
btn.next.mouseEnabled = true;
}
}
}
}

Something like this
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.utils.Dictionary;
public class Grid extends Sprite
{
private var _box : Dictionary = new Dictionary;
private var _conditions : Dictionary = new Dictionary;
private var _clicked : Dictionary = new Dictionary;
public function Grid()
{
var index:int = 0
var col:int = 3
var row:int = 3
for (var i:int = 0; i < row; i++)
{
for (var j:int = 0; j < col; j++)
{
//var cls:Class = Class(getDefinitionByName("Bitmap" + (index + 1) ));
//myImage = new Bitmap( new cls() );
var myImage_mc:MovieClip = new MovieClip();
//myImage_mc.addChild(myImage)
_box[ index ] = myImage_mc;
// Conditions for the 2nd and 3nd line etc.
if( i != 0 )
_conditions[ myImage_mc ] = _box[ index - col ];
// ------ DEBUG
myImage_mc.graphics.beginFill( 0xFFFFFF * Math.random() );
myImage_mc.graphics.drawRect(0,0,100,100);
myImage_mc.graphics.endFill();
// ------ END DEBUG
// Note i / j are invert from your example
myImage_mc.x = 100 + j * (myImage_mc.width + 10);
myImage_mc.y = 100 + i * (myImage_mc.height + 10);
this.addChild(myImage_mc);
myImage_mc.mouseEnabled = true
myImage_mc.addEventListener(MouseEvent.CLICK, onClick);
index++
}
}
}
protected function onClick(ev:MouseEvent):void
{
var neededClickElement : MovieClip = _conditions[ ev.currentTarget ];
// Check if we need an active movieclip before
if( neededClickElement != null && ! _clicked[ neededClickElement ] )
return;
_clicked[ ev.currentTarget ] = true;
ev.currentTarget.alpha = 0.1;
}
}
}

Related

How do I remove eventlisteners and objects from an array upon game completion?

I have written a drag and drop game and, for the most part, it works.
It runs and does what I need it to do.
However, I cannot figure out two things.
How to remove the toy objects from the screen and re-add them after game over.
How to remove the event listeners for dragging/collision action after game over has initiated.
At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed.
Does anyone have any idea what I am doing wrong?
I would love to figure this out but it is driving me crazy.
Any help would be great.
Here is my code ...
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.Font;
import flash.filters.GlowFilter;
public class MainGame extends MovieClip {
const BG_SPEED:int = 5;
const BG_MIN:int = -550;
const BG_MAX:int = 0;
const PBG_SPEED:int = 3;
var bg:BackGround = new BackGround;
var paraBg:ParaBg = new ParaBg;
var toybox:TargetBox = new TargetBox;
var toy:Toy = new Toy;
var tryAgain:TryAgain = new TryAgain;
var cheer:Cheer = new Cheer;
var eightBit:EightBit = new EightBit;
var countDown:Number = 30;
var myTimer:Timer = new Timer(1000, 30);
var myText:TextField = new TextField;
var myText2:TextField = new TextField;
var myTextFormat:TextFormat = new TextFormat;
var myTextFormat2:TextFormat = new TextFormat;
var font1:Font1 = new Font1;
var kids:Kids = new Kids;
var count:int = 0;
var finalScore:int = 0;
var score:Number = 0;
var toy1:Toy1 = new Toy1;
var toy2:Toy2 = new Toy2;
var toy3:Toy3 = new Toy3;
var toy4:Toy4 = new Toy4;
var toy5:Toy5 = new Toy5;
var toy6:Toy6 = new Toy6;
var toy7:Toy7 = new Toy7;
var toy8:Toy8 = new Toy8;
var toy9:Toy9 = new Toy9;
var toy10:Toy10 = new Toy10;
var toy11:Toy11 = new Toy11;
var toy12:Toy12 = new Toy12;
var toy13:Toy13 = new Toy13;
var toy14:Toy14 = new Toy14;
var toy15:Toy15 = new Toy15;
var toy16:Toy16 = new Toy16;
var toy17:Toy17 = new Toy17;
var toy18:Toy18 = new Toy18;
var toy19:Toy19 = new Toy19;
var toy20:Toy20 = new Toy20;
var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20);
public function mainGame():void
{
trace("HI");
eightBit.play(0, 9999);
addChildAt(paraBg, 0);
addChildAt(bg, 1);
addChildAt(kids, 2);
kids.x = 310;
kids.y = 200;
addChild(toy);
toy.x = 306;
toy.y = 133;
addChild(toybox);
toybox.x = 295;
toybox.y = 90;
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
for (var i:int = 0; i < toyArray.length; i++)
{
addToys(1140 * Math.random() + 20, 170 * Math.random() + 230);
}
}
public function bgScroll (e:Event)
{
stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.start();
e.target.addEventListener(Event.ENTER_FRAME, collision);
if (stage.mouseX > 600 && bg.x > BG_MIN)
{
bg.x -= BG_SPEED;
paraBg.x -= PBG_SPEED;
for (var m:int=0; m< toyArray.length; m++)
{
(toyArray[m] as MovieClip).x -=BG_SPEED
}
}
else if (stage.mouseX < 50 && bg.x < BG_MAX)
{
bg.x += BG_SPEED;
paraBg.x += PBG_SPEED;
for (var j:int=0; j< toyArray.length; j++)
{
(toyArray[j] as MovieClip).x +=BG_SPEED
}
}
for (var k:int = 0; k < toyArray.length; k++)
{
toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab);
}
bg.addEventListener(Event.ENTER_FRAME, bgScroll);
} // End of BGScroll
public function collision (e:Event)
{
for (var l:int=0; l< toyArray.length; l++)
{
if (toyArray[l].hitTestObject(toy))
{
removeChild(toyArray[l]);
toyArray[l].x=100000;
toybox.gotoAndPlay(2);
cheer.play(1, 1);
score = score + 10;
trace(score);
}
if (score == 200)
{
timerDone();
myTimer.stop();
}
}
}
public function arrayGrab(e:MouseEvent)
{
e.target.startDrag();
}
public function arrayDrop(e:MouseEvent)
{
stopDrag();
}
public function resetGame(e:Event):void {
trace("CLICK");
countDown = 30;
myText.text = "0" + countDown.toString();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.reset();
removeChild(tryAgain);
myText2.visible = false;
score = 0;
}
public function countdown(e:TimerEvent):void
{
if (countDown > 0)
{
countDown--;
}
if (countDown < 10)
{
myText.text = "0" + countDown.toString();
myText.x = 270;
displayText();
}
else if (countDown < 20 && countDown > 9)
{
myText.text = countDown.toString();
myText.x = 280;
displayText();
}
else
{
myText.text = countDown.toString();
myText.x = 270;
displayText();
}
} // end of countdown function
public function displayText():void
{
myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)];
addChild(myText);
myText.width = 500, myText.height = 50, myText.y = 10;
myTextFormat.size = 50, myTextFormat.font = font1.fontName;
myText.setTextFormat(myTextFormat);
}
public function displayText2():void
{ myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)];
addChild(myText2);
myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200;
myTextFormat2.size = 30, myTextFormat2.font = font1.fontName;
myText2.setTextFormat(myTextFormat2);
}
public function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
addChild(tryAgain);
tryAgain.x = 300;
tryAgain.y = 300;
tryAgain.addEventListener(MouseEvent.CLICK, resetGame);
}
} // End of class
} //End of package
Nevermind ... solved it.
Easiest was was to change
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
To
function addToys(xpos:int, ypos:int)
{
stage.addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
And then, in the timerDone function I added thisif statement ...
for (var m = 0; m < toyArray.length; m++) {
if (stage.contains(toyArray[m])) {
stage.removeChild(toyArray[m]);
}
Worked a treat!

addEventlistener, array, as linkage

I have added 10 movieclips with the AS linkage Box in this function. I've named the different instances layer1 to layer10
My question is, how can one add an eventlistener to, lets say, only layer4?
var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;
var _boxes:Array = [];
function Test()
{
for (var i:int = 0; i < NUM_BOXES; i++)
{
var box:Box = new Box( i + 1 );
box.y = (box.height + BOX_SPACING) * i;
box.name= "layer" +( i + 1);
box.buttonMode = true;
box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
addChild( box );
_boxes.push( box );
}
}
Building on bluebill1049's answer:
The if(number == 4) approach is not scalable, i.e. if you want a hundred layers to have listeners, you can not write an if statement for each layer. The simple solution would be:
var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;
var _boxes:Array = [];
//Any numbers in this array are assigned listeners
var layers_with_listeners:Array = [1, 4, 9];
function Test()
{
for (var i:int = 0; i < NUM_BOXES; i++)
{
var box:Box = new Box( i + 1 );
box.y = (box.height + BOX_SPACING) * i;
box.name= "layer" +( i + 1);
box.buttonMode = true;
if(layers_with_listeners.indexOf(i+1) != -1) {
box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
}
addChild( box );
_boxes.push( box );
}
}
var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;
var _boxes:Array = [];
var number:int;
function Test()
{
for (var i:int = 0; i < NUM_BOXES; i++)
{
number = i + 1;
var box:Box = new Box(number);
box.y = (box.height + BOX_SPACING) * i;
box.name= "layer" +(number);
box.buttonMode = true;
if(number == 4)
{
box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
}
addChild( box );
_boxes.push( box );
}
}

User interaction with Leapmotion AS3 library

I can connect the device and attach a custom cursor to one finger, but I can´t use any of the gestures to over/click a button or drag a sprite around, etc.
I´m using Starling in the project. To run this sample just create a Main.as, setup it with Starling and call this class.
My basic code:
package
{
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.events.LeapEvent;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.InteractionBox;
import com.leapmotion.leap.Pointable;
import com.leapmotion.leap.ScreenTapGesture;
import com.leapmotion.leap.Vector3;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.TouchEvent;
/**
* ...
* #author miau
*/
public class LeapController extends Sprite
{
private var _controller:Controller;
private var _cursor:Shape;
private var _screenTap:ScreenTapGesture;
private var _displayWidth:uint = 800;
private var _displayHeight:uint = 600;
public function LeapController()
{
addEventListener(Event.ADDED_TO_STAGE, _startController);
}
private function _startController(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, _startController);
//adding controller
_controller = new Controller();
_controller.addEventListener( LeapEvent.LEAPMOTION_INIT, onInit );
_controller.addEventListener( LeapEvent.LEAPMOTION_CONNECTED, onConnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_DISCONNECTED, onDisconnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_EXIT, onExit );
_controller.addEventListener( LeapEvent.LEAPMOTION_FRAME, onFrame );
//add test button
_testButton.x = stage.stageWidth / 2 - _testButton.width / 2;
_testButton.y = stage.stageHeight / 2 - _testButton.height / 2;
addChild(_testButton);
_testButton.touchable = true;
_testButton.addEventListener(TouchEvent.TOUCH, doSomething);
//draw ellipse as a cursor
_cursor = new Shape();
_cursor.graphics.lineStyle(6, 0xFFE24F);
_cursor.graphics.drawEllipse(0, 0, 80, 80);
addChild(_cursor);
}
private function onFrame(e:LeapEvent):void
{
trace("ON FRAME STARTED");
var frame:Frame = e.frame;
var interactionBox:InteractionBox = frame.interactionBox;
// Get the first hand
if(frame.hands.length > 0){
var hand:Hand = frame.hands[0];
var numpointables:int = e.frame.pointables.length;
var pointablesArray:Array = new Array();
if(frame.pointables.length > 0 && frame.pointables.length < 2){
//trace("number of pointables: "+frame.pointables[0]);
for(var j:int = 0; j < frame.pointables.length; j++){
//var pointer:DisplayObject = pointablesArray[j];
if(j < numpointables){
var pointable:Pointable = frame.pointables[j];
var normal:Vector3 = pointable.tipPosition;
var normalized:Vector3 = interactionBox.normalizePoint(normal);
//pointable.isFinger = true;
_cursor.x = normalized.x * _displayWidth;
_cursor.y = _displayHeight - (normalized.y * _displayHeight);
_cursor.visible = true;
}else if (j == 0) {
_cursor.visible = false;
}
}
}
}
}
private function onExit(e:LeapEvent):void
{
trace("ON EXIT STARTED");
}
private function onDisconnect(e:LeapEvent):void
{
trace("ON DISCONNECT STARTED");
}
private function onConnect(e:LeapEvent):void
{
trace("ON CONNECT STARTED");
_controller.enableGesture( Gesture.TYPE_SWIPE );
_controller.enableGesture( Gesture.TYPE_CIRCLE );
_controller.enableGesture( Gesture.TYPE_SCREEN_TAP );
_controller.enableGesture( Gesture.TYPE_KEY_TAP );
}
private function onInit(e:LeapEvent):void
{
trace("ON INIT STARTED");
}
private function doSomething(e:TouchEvent):void
{
trace("I WAS TOUCHED!!!");
}
}
}
If a good code Samaritan can update this code to perform a screen tap gesture (or any interacion with any object), I will really appreciate this a lot.
Regards!
controller.enableGesture(Gesture.TYPE_SWIPE);
controller.enableGesture(Gesture.TYPE_SCREEN_TAP);
if(controller.config().setFloat("Gesture.Swipe.MinLength", 200.0) && controller.config().setFloat("Gesture.Swipe.MinVelocity", 500)) controller.config().save();
if(controller.config().setFloat("Gesture.ScreenTap.MinForwardVelocity", 30.0) && controller.config().setFloat("Gesture.ScreenTap.HistorySeconds", .5) && controller.config().setFloat("Gesture.ScreenTap.MinDistance", 1.0)) controller.config().save();
//etc...
Then catch it in the frame event listener:
private function onFrame( event:LeapEvent ):void
{
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
for ( var i:int = 0; i < gestures.length; i++ )
{
var gesture:Gesture = gestures[ i ];
switch ( gesture.type )
{
case Gesture.TYPE_SCREEN_TAP:
var screentap:ScreenTapGesture = ScreenTapGesture ( gesture);
trace ("ScreenTapGesture-> x: " + Math.round(screentap.position.x ) + ", y: "+ Math.round( screentap.position.y));
break;
case Gesture.TYPE_SWIPE:
var screenSwipe:SwipeGesture = SwipeGesture(gesture);
if(gesture.state == Gesture.STATE_START) {
//
}
else if(gesture.state == Gesture.STATE_STOP) {
//
trace("SwipeGesture-> direction: "+screenSwipe.direction + ", duration: " + screenSwipe.duration);
}
break;
default:
trace( "Unknown gesture type." )
}
}
}
When the event occurs, check the coordinates translated to the stage/screen and whether a hit test returns true.
EDIT: Considering I have no idea how to reliable get the touch point x/y (or better: how to translate them to the correct screen coordinates), I would probably do something like this in my onFrame event:
private function onFrame(event:LeapEvent):void {
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
var posX:Number;
var posY:Number;
var s:Shape;
if(frame.pointables.length > 0) {
var currentVector:Vector3 = screen.intersectPointable(frame.pointables[0], true); //get normalized vector
posX = 1920 * currentVector.x - stage.x; //NOTE: I hardcoded the screen res value, you can get it like var w:int = leap.locatedScreens()[0].widthPixels();
posY = 1080 * ( 1 - currentVector.y ) - stage.y; //NOTE: I hardcoded the screen res value, you can get it like var h:int = leap.locatedScreens()[0].heightPixels();
}
for(var i:int = 0; i < gestures.length; i++) {
var gesture:Gesture = gestures[i];
if(gesture.type == Gesture.TYPE_SCREEN_TAP) {
if(posX >= _button1.x &&
posX <= _button1.x + _button1.width &&
posY >= _button1.y &&
posY <= _button1.y + _button1.height) {
s = new Shape();
s.graphics.beginFill(0x00FF00);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Lisa tocada!");
}
else {
s = new Shape();
s.graphics.beginFill(0xFF0000);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Fallaste! Intentalo otra vez, tiempo: "+new Date().getTime());
}
}
}
}

error while converting AS2 starfield code to AS3

I've tried to convert a nice AS2 script for starfirld effect to AS3 But i'm still getting strange errors
would really appreciate if any one could help me understand what am i doing wrong
here is the original AS2 code:
var stars = 100;
var maxSpeed = 16;
var minSpeed = 2;
var i = 0;
while (i < stars)
{
var mc = this.attachMovie("star", "star" + i, i);
mc._x = random(Stage.width);
mc._y = random(Stage.height);
mc.speed = random(maxSpeed - minSpeed) + minSpeed;
var size = random(2) + 6.000000E-001 * random(4);
mc._width = size;
mc._height = size;
++i;
} // end while
this.onEnterFrame = function ()
{
for (var _loc3 = 0; _loc3 < stars; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = Stage.height;
_loc2.speed = random(maxSpeed - minSpeed) + minSpeed;
_loc2._x = random(Stage.width);
} // end of for
};
and here is my AS3 version:
import flash.events.Event;
import flash.events.MouseEvent;
function starField():void
{
var stars:int = 100;
var maxSpeed:int = 16;
var minSpeed:int = 2;
var i:int = 0;
while (i < stars)
{
var mc = new Star();
addChild(mc)
mc._x = Math.random()(stage.stageWidth);
mc._y = Math.random()(stage.stageHeight);
mc.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
var size = Math.random()(2) + 6.000000E-001 * Math.random()(4);
mc._width = size;
mc._height = size;
++i;
} // end while
}
addEventListener(Event.ENTER_FRAME, update);
function update(_e:Event):void
{
for (var _loc3 = 0; _loc3 < 100; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = stage.stageHeight;
_loc2.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
_loc2._x = Math.random()(stage.stageWidth);
} // end of for
};
the error message I'm getting is: "TypeError: Error #1010: A term is undefined and has no properties. at _fla::MainTimeline/update()"
I understand it has a problem with the 'update' function but I'm net sure which term it refer to?
I'll bet a can of juice here is your problem:
var _loc2 = this["star" + _loc3];
put these into an associative array and access them from there.
#Discipol is right.
Just wanted to add a few more notes:
You can also use the display list to get the movie clip by name:
var _loc2:MovieClip = MovieClip(getChildByName("star" + _loc3));
You've got untyped variables and your are relying on MovieClip as a dynamic class to add properties (such as speed) at runtime. For a really simple project the impact is barely noticeable, but on the long run, for bigger projects, it's worth extending Sprite if you don't use the timeline and add the properties you need:
package {
import flash.display.Sprite;
import flash.events.Event;
public class Star extends Sprite {
private var speed:Number;
private var minSpeed:Number;
private var maxSpeed:Number;
public function Star(min:Number,max:Number) {
minSpeed = min;
maxSpeed = max;
var size = (Math.random()*2) + 1.82211880039 * (Math.random()*4);
width = size;
height = size;
this.addEventListener(Event.ADDED_TO_STAGE,reset);
}
private function reset(e:Event = null):void{
speed = (Math.random() * (maxSpeed-minSpeed)) + minSpeed;
x = Math.random() * stage.stageWidth;
if(e != null) y = Math.random() * stage.stageHeight;//initialized from added to stage event
else y = stage.stageHeight;//otherwise reset while updating
}
public function update():void{
if (y > 0) y -= speed;
else reset();
}
}
}
and the rest of the code would be as simple as:
var stars:int = 100;
var starClips:Vector.<Star> = new Vector.<Star>(stars,true);//a typed fixed vector is faster than a dynamically resizable untyped Array
for(var i:int = 0 ; i < stars; i++) starClips[i] = addChild(new Star(16,2)) as Star;
this.addEventListener(Event.ENTER_FRAME,updateStars);
function updateStars(e:Event):void{
for(var i:int = 0 ; i < stars; i++) starClips[i].update();
}

Action Script 3. How to remember last object x coordinates

I'm creating a flash game where objects are falling from the sky and the player needs to destroy them by clicking on them. But I have a problem, sometimes they spawning one on top of each other.
Here is an example what I mean:
Objects should be spawned near other, but not one on other.
Here is my constant vars:
public static const GRAVITY:Number = 3;
public static const HIT_TOLERANCE:Number = 50;
//Powerup
public static const APPLE_END_Y:Number = 640;
public static const APPLE_SPAWN_CHANCE:Number = 0.02; //per frame per second
public static const APPLE_START_Y:Number = 110;
public static const APPLE_SPAWN_START_X:Number = 50;
public static const APPLE_SPAWN_END_X:Number = 500;
//Scoring
public static const PLAYER_START_SCORE:Number = 0;
public static const SCORE_PER_APPLE:Number = 10;
Here is part of code where objects spawning:
private function update(evt:Event)
{
//Spawn new apples
if (Math.random() < randomChance)
{
//spawn x coordinates
var newPirmas = new Pirmas();
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newAntras = new Antras();
newAntras.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newTrecias = new Trecias();
newTrecias.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newApple = new Apple();
newApple.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
//spawn y coordinates
newPirmas.y = C.APPLE_START_Y;
newAntras.y = C.APPLE_START_Y;
newTrecias.y = C.APPLE_START_Y;
newApple.y = C.APPLE_START_Y;
newPirmas.addEventListener(MouseEvent.CLICK, onClick);
newAntras.addEventListener(MouseEvent.CLICK, onClick);
newTrecias.addEventListener(MouseEvent.CLICK, onClick);
newApple.addEventListener(MouseEvent.CLICK, onClick);
itemsToSpawn.push(newPirmas, newAntras, newTrecias, newApple);
}
}
As someone said: As for making sure they don't overlap, you can keep a history of their spawn points, and change how you get their random X value. Just iterate through the array of previous X values, and make sure the new one isn't within (oldX + (width/2)).
But I can't make It successfully, could you help me with keeping history of their spawn points? Thank you very much.
var t:Array = [];
t[0] = [APPLE_SPAWN_START_X, APPLE_SPAWN_END_X + APPLE_WIDTH/2];
t will keep the available intervals the you can generate new apple.
In the start time, there is no apple, and the t has only one interval, the starX of the interval is APPLE_SPAWN_START_X, the endX of the interval is APPLE_SPAWN_END_X + APP_WIDTH/2.
where you want to generate a new apple, you would find a availble interval in t, if we find the interval as mInterval(the interval could put in the apple, means endX - starX >= APPLE_WIDTH), then we could generate your new apple.
We just need to change the lines in you update function like
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
Instead
newPirmas.x = mInterval[0] + Math.random()*APPLE_WIDTH;
When we set newPirmas.x, we have break the mInterval and generate two new interval,
the values are [mInterval[0],newPirmas.x] and []newPirmas.x + APPLE_WIDTH, mInterval[0]],
so we need to delete the mInterval in t and put the two new intervals into t.
/**
*
* #return index of available interval in target array
*/
public static function findAvailInterval(target:Array, appleWidth:int):int {
if (target == null || target.length == 0) {
return -1;
}
var endX:int = 0;
var startX:int = 0;
var length:int = target.length;
for (var i:int = 0; i < length; i++) {
var temp:Array = target[i] as Array;
if (temp == null || temp.length < 2) {
return -1;
}
startX = temp[0];
endX = temp[1];
var intervalWidth:int = endX - startX;//the interval width
if (intervalWidth >= appleWidth) {//find an available one
return i;
}
}
return -1;
}
public static function breakInterval(target:Array, appleWidth:int, index:int):int {
var temp:Array = target[index];
var startX:int = temp[0];
var endX:int = temp[1];
var width:int = endX - startX;
var availableNewXRange:int = width - appleWidth;//the apple‘s max x, and the min x is startX
//random a position
var appleX:int = startX + availableNewXRange*Math.random();
var leftInterval:Array = [startX, appleX];//the left interval of apple
var rightInterval:Array = [appleX+appleWidth, endX];//the right interval of apple
//delete temp
target.splice(index, 1);
if (isAvailableInterval(leftInterval, appleWidth)) {
target.push(leftInterval);
}
if (isAvailableInterval(rightInterval, appleWidth)) {
target.push(rightInterval);
} else {
trace("vvv");
}
return appleX;
}
private static function isAvailableInterval(interval:Array, appleWidth:int):Boolean {
if (interval == null || interval.length < 2) {
return false;
}
return (interval[1] - interval[0]) >= appleWidth;
}
Put the three functions into a class A
var target:Array = [[0, 1000]];
var appWidth:int = 80;
for (var i:int = 0; i < 4; i++) {
var index:int = A.findAvailInterval(target, appWidth);
if (index != -1) {
var interval:Array = target[index];
RR.breakInterval(target, appWidth, index);
trace(interval);
}
}