Actionscript 3: Dynamically adding movieclips constrained to a container - actionscript-3

Last Edit: Resolved!
Well, i was unable to find the ENTIRE answer here but i finally got what i was after. thanks very much for all of your help and patience.
as a side note: i think i may have been having problems with using the int and Number types, upon closer inspection of my solution, i realised that Number was being used and not int. turns out number contains floating points and int doesn't. my numbers were probably rounding whenever i tried to fix this my self. for all i know, TDI's answer might have been spot on and the use of int for the padding might have accumulated rounded numbers.. Oh well, you learn something every day..
the correct code to constrain movie clips to a container movie clip (or sprite or whatever) in the fashion i was looking for is this:
var picContainer:PicContainer = new PicContainer();
picContainer.x = stage.stageWidth / 2 - picContainer.width / 2;
picContainer.y = stage.stageHeight / 2 - picContainer.height / 2;
addChild(picContainer);
var totalPics:int = 17;
var pic:Pic = new Pic(); //make an instance just to get its width
var xRange:Number = picContainer.width - pic.width;
var spacing:Number = xRange / (totalPics - 1);
//A little optimization: only need to calculate this number ONCE:
var yLoc:Number = picContainer.height / 2 - pic.height / 2;
for(var i:int = 0; i < totalPics; i++) {
pic = new Pic();
pic.x = i * spacing;
pic.y = yLoc;
picContainer.addChild(pic);
}
the logic is pretty simple, and i don't know why i couldn't get it my self, because i drew diagrams that say exactly this logic. however, i must not have put the numbers in the right places or i wouldn't have had to ask, would i ;P
BONUS CONTENT!
as an added bonus (if anyone finds this thread looking for answers..)
you could also have the 'pic's fan out from the center point (but they'd still be in order of left to right) by using this code:
var picContainer:PicContainer = new PicContainer();
picContainer.x = stage.stageWidth / 2 - picContainer.width / 2;
picContainer.y = stage.stageHeight / 2 - picContainer.height / 2;
addChild(picContainer);
var totalPics:int = 5;
var pic:Pic = new Pic(); //make an instance just to get its width
var padding:Number = (picContainer.width - (pic.width * totalPics)) / (totalPics + 1);
for(var i:int = 0; i < totalPics; i++) {
pic = new Pic();
pic.x = padding + i * (pic.width + padding);
pic.y = picContainer.height / 2 - pic.height / 2;
picContainer.addChild(pic);
}
Try it out, these make for great thumbnail dock engines!
First Edit: Well, there is some progress thanks to TDI but not a complete solution.
you see, the problem remains that the movie clips do not squash completely into the container, the last one or two are left sticking out.
example:
my revised code looks like this:
var newPicContainer:picContainer = new picContainer();
var newPic:pic;
var picwidth:int = 100;
var amountofpics:int = 22;
var i:int;
//add a container
addChild(newPicContainer);
//center our container
newPicContainer.x = (stage.stageWidth/2)- (newPicContainer.width/2);
newPicContainer.y = (stage.stageHeight/2)- (newPicContainer.height/2);
var totalpicwidth:int = picwidth*amountofpics;
var totalpadding:int = newPicContainer.width - totalpicwidth;
var paddingbetween:int = (totalpadding / amountofpics);
for (i = 0; i < amountofpics; ++i)
{
//make a new mc called newPic(and i's value) eg. newPic1
this['newPic' + i] = new pic();
this['newPic' + i].width = picwidth;
//add our pic to the container
newPicContainer.addChild(this['newPic' + i]);
//set the new pics X
if (i != 0)
{
// if i is not 0, set newpic(i)s x to the previous pic plus the previous pics width and add our dynamic padding
this['newPic' + i].x = this['newPic' + (i-1)].x + picwidth + paddingbetween;
}
else
{
this['newPic' + i].x = 0;
}
}
thanks again to anyone in advance!
Original Post:
Hello, First time posting here. I hope I'm not getting anything wrong . my problem is as follows:
I've got a pretty basic for loop that creates a 'thumbnail' and puts it next to the previous one (With a little padding) inside a containing movie clip.
var newPicContainer:picContainer = new picContainer();
var newPic:pic;
var amount:int = 9;
var i:int;
//Add our container
addChild(newPicContainer);
//center our container
newPicContainer.x = (stage.stageWidth/2)- (newPicContainer.width/2);
newPicContainer.y = (stage.stageHeight/2)- (newPicContainer.height/2);
for (i = 0; i < amount; ++i)
{
newPic = new pic();
newPicContainer.addChild(newPic);
//just so i know it's adding them..
trace(newPic.thisOne);
newPic.thisOne = i;
// set this one to its self (+5 for padding..) Times, the amount already placed.
newPic.x = (newPic.width+5) *i;
}
I'm wondering if there is some equation or 'magic math' that I can use to figure out what the length of the container is and have the 'thumbnails' be added relative to that number. basically squashing the thumbnails against each other to make them all fit inside..
something along the lines of:
newPic.x = (newPic.width *i) - stuff here to make it know not to go past the containing width;
I must admit i'm not too great with math and so this part of coding escapes me..
thanks to any takers in advance..

you can get the length of your container by either calling its width property explicitly:
//Container Width
newPicContainer.width;
or the newContainer is also the parent of the added pics:
//Container Width
newPic.parent.width;
then you need to get the total length occupied by you pics:
var arrayOfPics:array = [pic1, pic2, pic3, pic4, pic5];
var picsWidth:Number;
for each (var element:pic in arrayOfPics)
picsWidth =+ element.width;
after than you can subtract the length of the total pics from the container to know your available padding for separation:
var totalPadding:Number = newPicContainer.width - picsWidth;
now you can determine how much padding you can afford between the pics and both sides of the container by dividing the totalPadding by the number of pics, and add an extra padding for the end.
var padding:Number = totalPadding / arrayOfPics.length + 1;
now you can simply add your pics by including the padding
for (var i:int = 0; i < arrayOfPics.length; i++)
{
newPicContainer.addChild(arrayOfPics[i]);
(i == 0) ? arrayOfPics[i].x = padding : arrayOfPics[i].x = arrayOfPics[i - 1].x + arrayOfPics[i - 1].width + padding;
}

Try this...
//maximum available length
var maxLength:int;
// a single thumbnail width
var picWidth:int = 100;
// total number of pics in a container
var maxNumPics:int;
// as long as the maximum available length
// is inferior to the container length
// add a new thumbnail
while( maxLength < newPicContainer.length - 100 )
{
maxLength += 100;
maxNumPics += 1;
}
// calculate the amount of available padding.
var padding:Number = ( newPicContainer.length - maxLength )/ maxNumPics;
//add your thumbs
var picX:int;
for( var i:int ; i < maxNumPics ; ++i )
{
var newPic:Pic = new Pic();
newPic.x = picX;
picX += padding + picWidth;
newPicContainer.addChild( newPic );
}

I'd recommend you look at using the Flex framework (it's a Flash framework), it will make building this sort of view much easier.
You can set a container's layout property, so that items are placed in horizontal, vertical or tiled layouts, and then just add items to the container.
For more info on Flex look here
For info on Flex Layouts

Related

Fit array of movieclips in a fixed box in AS3

I have this array of movieclips (there can be only one but there can also be like 100) and a big movieclip on the stage with a fixed width and height (it can't be resized).
var boxWidth:int = 500
var boxHeight:int = 300
var box:MovieClip = new Movieclip;
box.graphics.beginFill(0x444444);
box.graphics.drawRect(
0,
0,
boxWidth,
boxHeight
);
box.graphics.endFill();
addChild(box);
var movieClipsArray:Array = []; //dynamic number of movieclips
var movieClipsSpacing:int = 10;
for(var i:String in movieClipsArray){
//calculate x, y, width, and height
box.addChild(movieClipsArray[i]);
}
How can I add all the movieclips from the array to the box, while fullfilling the following requirements?
The movieclips may be resized, but they have to keep their height/width ratio
The movieclips may not overlap
The movieclips may not exceed the borders of the box movieclip
There has to be some space between the movieclips (let's say, 10px)
The space of the box movieclip has to be used as efficiently as possible
The movieclips don't have to be in the same order, e.g movieClipsArray[0] could be at the left top, but also in the right bottom or somewhere in the center
I'm sorry for not having done much myself, but I just don't have any idea where to start
Dunno if I'm over complicating this at all, but I'd personally do something like this:
var boxWidth:int = 500;
var boxHeight:int = 300;
// each column and row of equally sized movieclip would be 5/7 and 3/7 of the width/height of the box respectively.
mcColumns = ((movieClipsArray.length / 7) * 5); // tells you how many columns
mcRows = ((movieClipsArray.length / 7) * 3); // tells you how many rows
//calculate width
var availableWidth = boxWidth - (mcColumns * 10); //width available after 10px spaces
var mcWidth:int = availableWidth / mcColumns; //width of each box
//calculate height
var availableHeight = boxHeight - (mcRows * 10); //height available after 10px spaces
var mcHeight:int = availableHeight / mcRows; //height of each box
for(var i:int = 0; i<mcColums; i++;){
for(var j:int = 0; i<mcRows; i++;){
//calculate x
movieClipsArray[i+j].width = mcWidth;
movieClipsArray[i+j].x = (availableWidth / mcWidth) * i;
movieClipsArray[i+j].x += 10 * i; //adds the space
//calculate y
movieClipsArray[i+j].height = mcHeight;
movieClipsArray[i+j].y = (availableHeight /mcWidth) * j;
movieClipsArray[i+j].y += 10 * j; //adds the space
box.addChild(movieClipsArray[i+j]);
}
}
Please bear in mind that I haven't checked this, I just wrote it to help set you on the right track.

SVG Raphaeljs Creating a grid of rectangles

I want to create a user defined grid of rectangles using SVG Raphaeljs. The method I am using at the moment is close to what I want it to do but its clearly not right.
My code as of now :
Creating the rectangles and trying to get them placed in an even grid of equal distance from each other
function startup() {
var paper = Raphael(50, 50, 1500, 875);
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 4; j++) {
var offset = i; // Stores the number to remove from the next variable to keep an even distance between shapes
var moveRight = (i + 20 - offset) * i; // new variable stores the amount to move the next rectangle along by adding 20 (distance in pixels
// to move to the right) to the loop counter i and then subtracting the offset which is the variable i
// before the + 20 was added and then multiplying it all by i again.
var moveDown = (j + 35 - offset) * j;
var c = paper.rect(moveRight, moveDown, 15, 20);
c.attr("fill", "#f00");
c.attr("stroke", "#fff");
}
}
}
The above currently produces this wonky grid as a result of my poor coding.
I need this to work in such a way that the user can enter the actual amount of rows and columns just by editing the values I put into the for loops and then using that number to change the distance each shape is placed,
As you can see I tried to do this by making a rough formula but I am now stuck, so any help is appreciated.
Ok, silly on my part. I've noticed a mistake and I've amended my code to the following:
function startup() {
var paper = Raphael(50, 50, 1500, 875);
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 4; j++) {
var offseti = i; // Stores the number to remove from the next variable to keep an even distance between shapes
var moveRight = (i + 20 - offseti) * i; // new variable stores the amount to move the next rectangle along by adding 20 (distance in pixels
// to move to the right) to the loop counter i and then subtracting the offset which is the variable i
var offsetj = j; // before the + 20 was added and then multiplying it all by i again.
var moveDown = (j + 25 - offsetj) * j;
var c = paper.rect(moveRight, moveDown, 15, 20);
c.attr("fill", "#f00");
c.attr("stroke", "#fff");
}
}
}

AS3 Dynamic Grid to HTML5 via CreateJS?

Basically, I've built a grid in AS3. Now, I would like to turn it into html5/JS with the new CreateJS ToolKit.
My problem - when I 'publish' to html, I get an empty canvas.
Here is my AS3 code:
var boxNum:int = 2151;
// we need to know how many columns our
// grid is going to have
var cols:int = 72;
// calculate how many rows we need based on
// boxNum and cols
var rows:int = Math.ceil(boxNum / cols);
// the number of boxes attached to the stage
var boxCount:int = 0;
for (var py:int = 0; py<rows; py++) {
for (var px:int = 0; px<cols; px++) {
// make sure we haven't exceeded boxNum
if (boxCount < boxNum) {
var box:Box = new Box();
box.x = 10 + (box.width + 2) * px;
box.y = 10 + (box.height + 2) * py;
addChild(box);
boxCount++;
}
}
}
AS3 code is not converted by the Toolkit. Currently, you have to write JavaScript, and wrap it in /*js */ tags on the timeline, or do all the coding outside of Flash.
Note that JavaScript doesn't support typed variables, you need to use "this" when referencing the current scope, and the "Box" will likely be available as a property of the generated "libs" object.
The Toolkit exported content should already set up a Ticker for you, and add your main Flash root (called "exportRoot" in the default exported code) to the Stage.
/* js
var boxNum = 2151;
var cols = 72;
var rows = Math.ceil(boxNum / cols);
var boxCount = 0;
for (var py = 0; py<rows; py++) {
for (var px = 0; px<cols; px++) {
if (boxCount < boxNum) {
var box = new libs.Box();
box.x = 10 + (box.width + 2) * px;
box.y = 10 + (box.height + 2) * py;
this.addChild(box);
boxCount++;
}
}
}
*/
Future versions of Flash will hopefully allow you to code this right on the timeline, instead of in a code comment block.

Moving movieclips across the stage on FrameEnter

I'm making an image gallery and I want to have a bunch of thumbnails on the bottom of the screen that smoothly slide from side to side when the mouse moves.
I'm working with a custom class for the container (Tiles) and a custom class for the thumbnails (ImageIcon).
I have a ComboBox which allows users to to choose a gallery. When the user chooses a gallery, the following code is run and the thumbnails should reload. The problem here is that the icons appear on top of each other instead of side by side, also switching categories should remove the old one (see the first for loop), but it does not. Also, the Icons are not animating properly. The animation code is below as well. Right now, only one of the icons will move. The icons should move in order from side to side, stopping when the last few icons hit the edge of the screen, so that they don't get "lost" somewhere off to the side.
Gallery Loader Code:
public function loadCategory(xml:XML = null) {
if (xml != null) {
dp = new DataProvider(xml);
for (var k:int = 0; k < this.numChildren; k++) {
this.removeChild(this.getChildAt(k));
}
var black:DropShadowFilter = new DropShadowFilter(0, 45, 0x000000, 1, 3, 3, 1, 1);
var white:DropShadowFilter = new DropShadowFilter(0, 45, 0xFFFFFF, 1, 2, 2, 1, 1);
for (var i:int = 0; i < dp.length; i++) {
var imgicon:ImageIcon = new ImageIcon();
imgicon.addEventListener(MouseEvent.CLICK, showImage);
imgicon.width = 100;
imgicon.x = (i * (imgicon.width + 20));
imgicon.path = dp.getItemAt(i).data;
imgicon.loadIcon();
imgicon.filters = [black, white];
stage.addEventListener(Event.ENTER_FRAME, moveIcon);
this.addChild(imgicon);
}
} else {
//Failed to load XML
}
}
Icon Animation Code:
public function moveIcon(e:Event){
var speed = 0;
speed = Math.floor(Math.abs(this.mouseX/20));
var image = this.getChildAt(k);
var imagebox = image.width + 20;
var edge:Number = (800/2);
if (this.mouseX > 0) {
for (var k:int = 0; k < this.numChildren; k++) {
if (image.x - (imagebox/2) + speed < -edge + (k * imagebox)) {
speed = 0;
}
image.rotationY = Math.floor(image.x/20);
image.x -= Math.floor(speed);
}
} else {
for (var j = this.numChildren; j >= 0; j--) {
if (image.x + speed > edge - ((imagebox * j) )) {
speed = 0;
}
image.rotationY = Math.floor(image.x/20);
image.x += Math.floor(speed);
}
}
}
As I see it, you have three questions (You should have put these at the end of your question instead of "What is wrong with my code?"). One of the main principles of programming is breaking problems into smaller parts.
How do I line up the ImageIcon beside each other?
How do I remove the old ImageIcon, when switching categories?
How do I animate ALL the ImageIcons together, based on the mouse position, with constraints on either side?
Question 1
I can't see anything wrong, but just check that when you are setting imgicon.x, that imgicon.width is actually set.
Question 2
Instead of relying on numChildren and getChildAt(), I would create a currentIcons array member variable, and when you create a new ImageIcon, just push it onto the array. Then when you want to remove them, you can just loop through the array like this:
for each (var cIcon:ImageIcon in currentIcons)
{
cIcon.removeEventListener(MouseEvent.CLICK, showImage);
removeChild(cIcon);
}
currentIcons = [];
As you can see, I am also removing any listeners that I have added. This is best practice. Then clearing the array when I have removed all the icons.
Question 3
I can see a few things wrong with your code. First, in the line where image is set, k is not set yet!
Here you can also use the currentIcons array, but you probably can't use a for each in loop, because that gives you the items out of order. Just a normal for loop will be better.
I haven't tested this code for the moveIcon method, but the idea should work. You may have to tweek it though:
public function moveIcon(e:Event):void
{
var speed:Number = Math.floor(this.mouseX / 20); // Removed "abs".
var imageBox:Number = currentIcons[0].width;
var edge:Number = 800 / 2;
for (var i:int = 0; i < currentIcons.length; i++)
{
var image:ImageIcon = currentIcons[i] as ImageIcon;
image.x += speed;
image.rotationY = Math.floor(image.x / 20);
var min:int = -edge + (i * imagebox);
if (image.x < min) image.x = min;
var max:int = edge - (imagebox * i);
if (image.x > max) image.x = max;
}
}
EDIT* Sorry, it was supposed to be a greater than in the last if statement, but I had a less than by accident.

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