How to resize the the animating sprite in cocos2d-x - cocos2d-x

I want to change the size of a Sprite which is animating. How can I do this ? I tried to change its size by using setScale property but it is not working here. where I am doing wrong ?
CCArray* frames = CCArray::createWithCapacity(3);
CCSpriteFrameCache* frameCache = CCSpriteFrameCache::sharedSpriteFrameCache();
char file[100] = {0};
for (int i = 0; i < 3; i++)
{
sprintf(file, "bird%d.png", i);
CCSpriteFrame* frame = frameCache->spriteFrameByName(file);
frames->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(frames, 0.1);
CCAnimate* animate = CCAnimate::create(animation);
CCRepeatForever* repeat = CCRepeatForever::create(animate);
bird->runAction(repeat);
bird->setScale(0.7);

Try like this. It's working fine.
CCSprite* pSprite = CCSprite::create("pic2.png");
pSprite->setPosition( ccp(size.width/2, size.height/2) );
this->addChild(pSprite, 0);
//Animation
CCAnimation *animate = CCAnimation::create();
for (int i = 1; i <=3; i++)
{
char frameName[128] = {0};
sprintf(frameName, "pic%d.png", i);
animate->addSpriteFrameWithFileName(frameName) ;
}
animate->setDelayPerUnit(0.1f); // This animation contains 3 frames, will continuous 2.8 seconds.
animate->setRestoreOriginalFrame(true); // Return to the 1st frame after the 3rd frame is played.
CCAnimate *animaction = CCAnimate::create(animate);
CCRepeatForever *reptaction = CCRepeatForever::create(animaction);
pSprite->runAction(reptaction);
pSprite->setScale(0.3);

Related

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

createJS caching tilemap background does not render

If I don't cache the container of tiles after creating the map, I can see them rendered to the canvas:
function createWorld() {
background = new createjs.Container();
for (var y = 0; y < mapWidth; y++) {
for (var x = 0; x < mapHeight; x++) {
var tile = new createjs.Bitmap('images/tile.png');
tile.x = x * 28;
tile.y = y * 30;
background.addChild(tile);
}
}
//background.cache(0, 0, mapWidth, mapHeight);
stage.addChild(background);
}
If I do cache the background container of tile children, it won't render
function createWorld() {
background = new createjs.Container();
for (var y = 0; y < mapWidth; y++) {
for (var x = 0; x < mapHeight; x++) {
var tile = new createjs.Bitmap('images/tile.png');
tile.x = x * 28;
tile.y = y * 30;
background.addChild(tile);
}
}
background.cache(0, 0, mapWidth, mapHeight);
stage.addChild(background);
}
Why?
This is probably because that even when preloaded, images may not be available synchronously if you use a path to create them. If you aren't caching them, then they wouldn't show up immediately when the stage is updated -- but if you ticked the stage, they might appear to load instantly (they just take a frame or so).
I recommend you preload them, either internally, or using something like PreloadJS. Then pass the loaded instance to the bitmaps instead.
var img = document.createElement("img");
img.onload = draw;
img.src = "images/tile.png";
function draw() {
// loop
var bmp = new createjs.Bitmap(img); // Use a reference instead of a path
}
Note that this also reduces overhead, since only one image is created, and all the Bitmaps share a reference to it.
If all your tiles are the same, you might want to look at the Graphics.beginBitmapFill() method. http://www.createjs.com/Docs/EaselJS/classes/Graphics.html#method_beginBitmapFill

About generating sound waveform in an ActionScript 3 Bitmap

I am generating Bitmap object to show the sound waveform of a loaded sound. The bitmap is 1024x120 and after it has been generated I shrink its size to 655x120. My problem is the player that loads the bitmap in task manager becomes 260MB heavy.
I am also adding some gradients and I also cache it as bitmap, but if I remove this properties I dont get any big difference in size.
I also can try to small its size but still I think the bitmap will be big.
Any idea how to compress or whatever solution to solve this problem?
thanks
Here is some code
These are the sound and Bitmap settigns of the function that generate the bitmap.
public function generateBitmap(snd:Sound):void
{
samples = new ByteArray();
buffer = new BitmapData(1024, 120, false, backColor);
screen = new Bitmap(buffer);
rect = new Rectangle(0, 0, 1, 0);
var left:Number;
var right:Number;
screen.x = 0;
screen.y = 0;
screen.width = 655;
screen.height = 120;
buffer.fillRect( buffer.rect, backColor );
Now I am doing some samples extraction
var extract:Number = Math.floor ((snd.length / 1000) * 44100);
playingTime = snd.length;
ratio = playingTime / buffer.width;
var lng:Number = snd.extract(samples, extract);
samples.position = 0;
step = samples.length / 4096;
do
{
step-- ;
}
while ( step % 4 );
Follows the drawing method of the bitmap.
for (var c:int = 0; c < 4096; c++)
{
rect.x = c / 4;
left = samples.readFloat() * 25;
right = samples.readFloat() * 25;
samples.position = c * step;
// left channel
if (left > 0)
{
rect.y = 30 - left;
rect.height = left;
}
else
{
rect.y = 30;
rect.height = -left;
}
buffer.fillRect( rect, leftChColor );
// right channel
if (right > 0)
{
rect.y = 80 - right;
rect.height = right;
}
else
{
rect.y = 80;
rect.height = -right;
}
buffer.fillRect( rect, rightChColor );
}
screen.width = screenWidth;
screen.height = screenHeight;
addChild( screen );
}
Here is a reference of the code I have used. Tried it without my stuff in the player and get 193MB of RAM just for the flash player. So the code needs I guess the code needs refinement. Any idea or othere method to do the same stuff without eating so much RAM?
Before this line:
buffer = new BitmapData(1024, 120, false, backColor);
Add:
if ( buffer ) { buffer.dispose(); buffer = null; }
buffer = new BitmapData(1024, 120, false, backColor);

8 queens problem

I am trying to solve the 8 queens problem (where you select a space and it will put down 8 queens so that none of them will hit each other) but i am having trouble making the chess board.
right now i have this
var chessBoard:Array = new Array();
chessBoard["row1"] = [1,0,1,0,1,0,1,0];
chessBoard["row2"] = [0,1,0,1,0,1,0,1];
chessBoard["row3"] = [1,0,1,0,1,0,1,0];
chessBoard["row4"] = [0,1,0,1,0,1,0,1];
chessBoard["row5"] = [1,0,1,0,1,0,1,0];
chessBoard["row6"] = [0,1,0,1,0,1,0,1];
chessBoard["row7"] = [1,0,1,0,1,0,1,0];
chessBoard["row8"] = [0,1,0,1,0,1,0,1];
and i need to know two things
a) will i be able to use this for the problem (will i be able to have it check if any queens will collide by its array coordinates)
b) how do i draw the squares on the chess board to correspond with the numbers
var chessBoard:Array = new Array();
// Setup the array
for(var i:int = 0; i < 4; i++)
{
chessBoard.push(new Array(1,0,1,0,1,0,1,0));
chessBoard.push(new Array(0,1,0,1,0,1,0,1));
}
// Size of the tile
var tileSize:int = 20;
function createChessBoard():void
{
// Itterate through the "chessBoard"-array
for(var i:int = 0; i < chessBoard.length; i++)
{
// Itterate through the arrays in the "chessBoard"-array
for(var j:int = 0; j < chessBoard[i].length; j++)
{
// Create new tile
var tile:Sprite = new Sprite();
// Create the color variable and check to see what value to put
// in it dependingin the value of the current itteration - 1 or 0
var tileColor:int = chessBoard[i][j] * 0xffffff;
// Tile-coloring-setup-thingie-routine
tile.graphics.beginFill(tileColor);
tile.graphics.drawRect(0, 0, tileSize, tileSize);
tile.graphics.endFill();
// Tile positioning
tile.x = j * tileSize;
tile.y = i * tileSize;
// Adding tile to the displaylist
addChild(tile);
}
}
}
// Run function
createChessBoard();
You can assume that cell is black when sum of its coordinates is odd and white if even:
function getColor(x, y) {
return (x + y) % 2 == 0 ? 0 : 1;
}
// or even
function getColor(x, y) {
return (x + y) % 2;
}
You could start with creating a Square class, this would enable you to give specific properties to each Square. You want to avoid having two pieces on one square for instance, you want to set the color, also you would need to know the coordinates such as a1, c4 etc...
To draw your Chessboard, you could create rows of Squares.
private function squares:Array = [];
private function addRow( black:Boolean , _y:int , rowName:String ):void
{
for( var i:int ; i < 8 ; ++i )
{
var sq:Square = new Square();
//alternate colors
if( black )
sq.color = 0;
else
sq.color = 0xffffff;
black = !black;
sq.x = i* sq.width;
sq.y = _y;
//save square Chess coordinates
sq.coord = {letter: rowName , number: i + 1}
addChild(sq);
//add the Square instance to an Array for further reference
squares.push( sq );
}
}
Then simply add the rows
private function createBoard():void
{
var black:Boolean;
var letters:Array = [ a , b , c , d , e , f , g , h ]
for( var i:int ; i < 8 ; ++i )
{
addRow( black , i * squareSize , letters[i] );
black = !black;
}
}
To add a Queen to a specific Square instance , use the squares Array.

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.