AS3: can't addchild indexed movieclips into a sprite - actionscript-3

I'm creating a dynamic blocked terrain in flash (AS3), and everything goes fine with it, the terrain is correctly placed. But I need to include collisions and I want the blocks to be within a movieclip (sprite), so I can test the collision with the terrain itself.
Ps: I don't know if it would be good to test the collisions with each block individually because I'll use a enterframe function and the block generation is dynamic.
The problem I'm facing is that I have a sprite called blockHolder, but I can't addChild the blocks to it.
Here's the code (I simplified it so we have the blocks being created in cascade if you addChild them into the stage directly, like addChild(clonedSquare).
The error I'm receiving:
TypeError: Error #1009: Can't access property or method of a null object reference.
var blockHolder:Sprite = new Sprite();
var clonedSquare = new square();
var lowestPoint:int = 10;
var highestPoint:int = 20;
var areaLenght:int = 10;
function createLvl():void
{
for (var i:Number = 0; i<(areaLenght); i++)
{
clonedSquare = new square();
clonedSquare.x = i * clonedSquare.width;
//sets the height of the first block
if (i == 0)
{
var firstY:Number = Math.ceil(Math.random()*((lowestPoint-highestPoint))+highestPoint)*clonedSquare.height;
clonedSquare.y = firstY;
trace("terrain begins " + firstY + " px down");
}
else
{
var previousId:Number = i - 1;
clonedSquare.y = getChildByName("newSquare"+previousId).y + clonedSquare.height;
}
//sets the entity (block) name based on the iteration
clonedSquare.name = "newSquare" + i;
//adds the cloned square
blockHolder.addChild(clonedSquare);
}
addChild(blockHolder);
}
createLvl();

Well I fixed the error. I am still not clear as to what you're asking for. Basically I add each block to an array and reference the block that way. Your clonedSquare.y = getChildByName("newSquare"+previousId).y + clonedSquare.height; was throwing the error. Also your firstY was placing the first block way off my stage so I just set it to 0 as firstY
var blockHolder:Sprite = new Sprite();
var squares:Array = [];
var lowestPoint:int = 10;
var highestPoint:int = 20;
var areaLenght:int = 10;
function createLvl():void
{
for (var i:Number = 0; i<(areaLenght); i++)
{
var clonedSquare = new square();
clonedSquare.x = i * clonedSquare.width;
if (i == 0)
{
var firstY:Number = Math.ceil(Math.random()*((lowestPoint-highestPoint))+highestPoint)*clonedSquare.height;
//clonedSquare.y = firstY;
clonedSquare.y = 0;
trace("terrain begins " + firstY + " px down");
}
else
{
clonedSquare.y = squares[i - 1].y + clonedSquare.height;
}
blockHolder.addChild(clonedSquare);
squares.push(clonedSquare);
}
addChild(blockHolder);
}
createLvl();

Related

AS3 How can I get back the object that being dragged to Item

I have board with 16 objects(MovieClip), every one of them have a unique instance name (slot1-16).
I'm trying to make a drag and drop code that return the instance name of the object dragged on it.
function fl_ReleaseToDrop(evt:MouseEvent):void {
var object = evt.currentTarget;
if(object is textBox || object is UILoader)
{
for(var i:int = 1; i < 16; i++){
//Checks the correct drop target
if (object.hitTestObject(getChildByName("slot" + i)))
{
trace("slot" + i);
slot(getChildByName("slot" + i)).gotoAndStop(3);
}else{
object.x = xPos; //If not, return the clip to its original position
object.y = yPos;
}
}
object.stopDrag();
}
}
What really happened is that the only place that i can drag in to is slot1, other slots are not working.
In your current code, if the 1st hit test with slot1 object fails, you return your dragged object to its original position and of course all the hit tests with other slots will fail.
So you should return your object to its original position just after doing the hit test with all objects. You can use, for example, a Boolean var to know if there is at least one succeeded hit test, in that case you don't need to return your dragged object to its original position :
function fl_ReleaseToDrop(evt:MouseEvent):void
{
var object = evt.currentTarget;
var hit_test:Boolean = false;
if(object is textBox || object is UILoader)
{
for(var i:int = 1; i < 16; i++)
{
if (object.hitTestObject(getChildByName("slot" + i)))
{
hit_test = true;
slot(getChildByName("slot" + i)).gotoAndStop(3);
}
}
if(!hit_test)
{
object.x = xPos;
object.y = yPos;
}
object.stopDrag();
}
}
Hope that can help.

How to place multiple bitmaps in a scrollable rectangle? AS3

This code builds a palette of tiles for use in a map maker program. It takes in an array set by its parent and uses the bitmaps(from the objects) in that array to display a grid of tiles. Right now it only does a 5x5 grid, but what if there are more than 25 tiles in my tileSet? I want to display only the 5x5 tile grid, but be able to scroll through the images. I imagine that I need to make another rectangle to use as its mask and use a ScrollBar to make it scrollRect, but I can't get this working. Please Help.
public function Palette(X:uint, Y:uint, tileSet:Array)
{
addChild(handleGraphics);
var palette:Rectangle = new Rectangle(X, Y, 5*32, tileSet.length*32); //Default size is 5x5 tiles.
handleGraphics.DrawGrid(32,palette.x,palette.y,5,5);
var counter:int = 0;
for(var i:int = 0; i < 5; i++)
{
paletteArray[i] = [];
for(var u:int = 0; u < 5; u++)
{
if(counter >= tileSet.length)
{
counter = 0; //Which frame to show?
}
var b:Bitmap = new Bitmap(tileSet[counter].Graphic);
b.x = (palette.x) + 32 * u; //Align with palette Rectangle.
b.y = (palette.y) + 32 * i; ///////////////////////////////
addChild(b);
var tileObj:Object = new Object();
tileObj.Name = tileSet[counter].Name;
tileObj.Frame = tileSet[counter].Frame;
tileObj.Graphic = tileSet[counter].Graphic;
paletteArray[i].push(tileObj);
setChildIndex(b, 0); //Under grid.
counter++;
}
}
ActivatePaletteListeners();
}
This code works great for a tileSet array that has less than 25 objects. It loops and shows them continuously until it hits 25. I could do without this I guess, but it is a neat affect.
In another class (HandleTiles) I cycle through my tileSet MovieClip and use each frame to create a new object for each tile.
public function GetPaletteTiles(MC:MovieClip)
{
if (tileArray != null)
{
tileArray.length = 0;
}
for(var i:int = 1; i <= MC.totalFrames; i++)
{
MC.gotoAndStop(i); //Change frame for new info.
var tileObj:Object = new Object(); //The object to push to an array of tiles.
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(MC); //Graphic data from sampleTS.
tileObj.Name = MC.currentFrameLabel;
tileObj.Frame = MC.currentFrame;
tileObj.Graphic = graphicData;
tileArray.push(tileObj);
}
BuildIndexArray(15, 20); //Default size 15 x 20.
}
And here I set the tileSet to use
private function ChangeActiveTileset(Mc:MovieClip)
{
activeTileset = Mc;
GetPaletteTiles(activeTileset);
UpdatePalette();
}
I can change the tileSet with a comboBox. That's why I tear down the tileArray every time I call GetPaletteTiles(). Each tileSet is a different MovieClip, like Buildings, Samples, InTheCity, etc.
Sorry I didn't have time to get this code together earlier. Here's tiling code pieces. Because you're using rectangle and you have to stay under max dimensions you have to move the source mc. I think you already know everything else in there.
// set the bmp dimensions to device screensize to prevent exceeding device's max bmp dimensions
if (bStagePortrait) {
iTileWidth = Capabilities.screenResolutionX;
iTileHeight = Capabilities.screenResolutionY;
} else {
iTileWidth = Capabilities.screenResolutionY;
iTileHeight = Capabilities.screenResolutionX;
}
// mcList.mcListVector is the source mc - a regular mc containing mcs, jpgs, dynamic text, vector shapes, etc.
// mcList.mcListBmp is an empty mc
aListTiles = new Array();
iNumberOfTiles = Math.ceil(mcList.height / iTileHeight);
for (i = 0; i < iNumberOfTiles; i++) {
var bmpTile: Bitmap;
// move the source mc
mcList.mcListVector.y = -(i * iTileHeight);
bmpTile = fDrawTile(mcList, 0, 0, iTileWidth, iTileHeight);
mcList.mcListBmp.addChild(bmpTile);
bmpTile.x = 0;
bmpTile.y = (i * iTileHeight);
aListTiles.push(bmpTile);
}
// remove the regular mc
mcList.mcListVector.removeChild(mcList.mcListVector.mcPic);
mcList.mcListVector.mcPic = null;
mcList.removeChild(mcList.mcListVector);
mcList.mcListVector = null;
}
function fDrawTile(pClip: MovieClip, pX: int, pY: int, pWidth: int, pHeight: int): Bitmap {
trace("fDrawTile: " + pX + "," + pY + " " + pWidth + "," + pHeight);
var rectTemp: Rectangle = new Rectangle(pX, pY, pWidth, pHeight);
var bdClip: BitmapData = new BitmapData(pWidth, pHeight, true, 0x00000000);
var bdTemp: BitmapData = new BitmapData(pWidth, pHeight, true, 0x00000000);
bdClip.draw(pClip, null, null, null, rectTemp, true);
bdTemp.copyPixels(bdClip, rectTemp, new Point(0, 0));
var bmpReturn: Bitmap = new Bitmap(bdTemp, "auto", true);
return bmpReturn;
}

How to call a variable of a function using concatenation (AS3)

I need to acess a variable inside this function using concatenation, following this example:
public function movePlates():void
{
var plate1:Plate;
var plate2:Plate;
var cont:uint = 0;
for (var i:uint = 0; i < LAYER_PLATES.numChildren; i++)
{
var tempPlate:Plate = LAYER_PLATES.getChildAt(i) as Plate;
if (tempPlate.selected)
{
cont ++;
this["plate" + cont] = LAYER_PLATES.getChildAt(i) as Plate;
}
}
}
EDIT:
public function testFunction():void
{
var test1:Sprite = new Sprite();
var test2:Sprite = new Sprite();
var tempNumber:Number;
this.addChild(test1);
test1.x = 100;
this.addChild(test2);
test2.x = 200;
for (var i:uint = 1; i <= 2; i++)
{
tempNumber += this["test" + i].x;
}
trace("tempNumber: " + tempNumber);
}
If i run the code like this, the line this["test" + i] returns a variable of the class. I need the local variable, the variable of the function.
Your loop on first step access plate0 this will cause not found error, if plate0 is not explicitly defined as class member variable or if class is not defined as dynamic. Same thing will happen for plate3, plate4, plate5... in case LAYER_PLATES.numChildren is more than 3.
EDIT:
Thanks to #Smolniy he corrected my answer plate0 is never accessed because cont is incremented before first access. So as he mentioned problem should be on plate3
You don't get the local variable with [] notation. your case has many solutions. You can use dictionary, or getChildAt() function:
function testFunction():void
{
var dict = new Dictionary(true);
var test1:Sprite = new Sprite();
var test2:Sprite = new Sprite();
var tempNumber:Number = 0;
addChild(test1);
dict[test1] = test1.x = 100;
addChild(test2);
dict[test2] = test2.x = 200;
for (var s:* in dict)
{
tempNumber += s.x;
//or tempNumber += dict[s];
}
trace("tempNumber: " + tempNumber);
};

Intermittent/staggered loading of an object

I've just recently tried my hand at actionscript 3 and have come across a road block.
How do I go about rendering the cubes (cube1) intermittently, ie. staggered loading. I need the cubes to load a split second from each other.
Below is a snippet of what I have so far:
var rows:int = 5;
var cols:int = 3;
var spacery:int = 100;
var spacerx:int = 120;
var box_count:int = 8;
for(var i:int; i < box_count; i++) {
cube1 = new Cube(ml,100,10,80,1,1,1);
cube1.y = ((i % rows)) * (cube1.x + spacery);
cube1.x = Math.floor(i/rows) * (cube1.x +spacerx);
cube1.z = 0;
bigBox.addChild(cube1);
}
//Create an array out side the function; as a global (instance) variable:
var cubes:Array = [];
//instead of bigBox.addChild(cube1), store them in the array:
cubes.push(cube1);
//initialize a timer outside after for loop
//Fire every 100 milliseconds, box_count times
var timer:Timer = new Timer(100, box_count);
timer.addEventListener(TimerEvent.TIMER, onTick);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTickDone);
function onTick(e:Event):void
{
bigBox.addChild(cubes[timer.currentCount]);
}
function onTickDone(e:Event):void
{
cubes = null;
timer.removeEventListener(TimerEvent.TIMER, onTick);
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTickDone);
timer = null;
}

How to modify position of children inside loop in AS3

I'm trying to make a dynamic image gallery from and xml. From my tutorials, right now i've got it so it will constantly add the next thumbnail below the other, which is fine, but I'm trying to figure out how to make it that once it reaches a certain y coordinate, it will move the x coordinate over and stack them again. So that rather one long list of thumbs, it will be a side by side stack. For some reason, I can't get it in my head how something like this would work. My goal is to have a side by side stack that I will end up putting in a movie clip that will be masked to show only 2 stacks at a time. Then when clicking a button will slide it over. I was planning to use the "movieclip.length" to calculate how far over to move it, but i haven't gotten that far yet. This is what I got:
var gallery_xml:XML;
var xmlReq:URLRequest = new URLRequest("xml/content.xml");
var xmlLoader:URLLoader = new URLLoader();
var imageLoader:Loader;
function xmlLoaded(event:Event):void
{
gallery_xml = new XML(xmlLoader.data);
info_txt.text = gallery_xml.screenshots.image[0].attribute("thumb");
for(var i:int = 0; i < gallery_xml.screenshots.image.length(); i++)
{
imageLoader = new Loader();
imageLoader.load(new URLRequest(gallery_xml.screenshots.image[i].attribute("thumb")));
imageLoader.x = 0;
imageLoader.y = i * 70 + 25;
imageLoader.name = gallery_xml.screenshots.image[i].attribute("src");
addChild(imageLoader);
imageLoader.addEventListener(MouseEvent.CLICK, showPicture);
}
}
xmlLoader.load(xmlReq);
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function showPicture(event:MouseEvent):void
{
imageLoader = new Loader();
imageLoader.load(new URLRequest(event.target.name));
imageLoader.x = 200;
imageLoader.y = 25;
addChild(imageLoader);
}
I can't seem to wrap my head around what I can do to move things over dynamically without having to write a custom if for each set of positions.. I get the feeling I've totally forgotten how to do algebra.
I'd suggest one of the following two solutions (untested):
var next_x:Number = 0.0;
var next_y:Number = 25.0;
for (var i:int = 0; i < gallery_xml.screenshots.image.length(); ++i)
{
// ...
imageLoader.y = next_y;
imageLoader.x = next_x;
next_y += 70;
if (next_y > THRESHOLD)
{
next_x += X_OFFSET;
next_y = 25.0;
}
}
That is, just keep track of where your next image will be placed and adjust that coordinate accordingly when you exceed thresholds. If you want to use your i variable, you'll have to calculate what row and column the image will be placed at:
for (var i:int = 0; i < gallery_xml.screenshots.image.length(); ++i)
{
// ...
var row:int = i % MAX_ITEMS_PER_COLUMN;
var column:int = i / MAX_ITEMS_PER_COLUMN;
imageLoader.y = 25 + row * 70;
imageLoader.x = column * COLUMN_WIDTH;
}