SpriteAnimation in COCOS2DX with plist - cocos2d-x

hello i am using this code for animating a sprite using cocos2dx.
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("suhas.plist");
CCLog("#########################");
CCSpriteBatchNode *spriteSheet = CCSpriteBatchNode::batchNodeWithFile("suhas.PNG");
CCLog("*********************************");
this->addChild(spriteSheet);
CCLog("*********************************");
CCArray *bearArray = new CCArray();
for(int i = 1; i <= 8; i++)
{
CCLog("*********************************");
char name[32] = {0};
sprintf(name, "bear%d.png",i);
bearArray->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name));
}
CCAnimation *walkAnim = CCAnimation::animationWithSpriteFrames(bearArray, 0.1f);
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCSprite *bear = CCSprite::spriteWithSpriteFrameName("bear1.png");
bear->setPosition(ccp(size.width/2, size.height/2));
CCAction *walkAction = CCRepeatForever::actionWithAction(CCAnimate::actionWithAnimation(walkAnim));
bear->runAction(walkAction);
spriteSheet->addChild(bear);
return true;
But my code in crashing. and giving error
cocos2d: CCSpriteFrameCache: Trying to use file D:\cocos2dnew\SPRITEAnimDemo\Resources\suhas.png as texture
First-chance exception at 0x00000000 in SPRITEAnimDemo.win32.exe: 0xC0000005: Access violation.
Unhandled exception at 0x00000000 in SPRITEAnimDemo.win32.exe: 0xC0000005: Access violation.
The program '[1012] SPRITEAnimDemo.win32.exe: Native' has exited with code -1073741819 (0xc0000005).
I tried on google for solving this problem. Please help me.

Change this line
*spriteSheet = CCSpriteBatchNode::batchNodeWithFile("suhas.PNG");
with
*spriteSheet = CCSpriteBatchNode::batchNodeWithFile("suhas.png");

In newer version of cocos2d-x you can add batchnode first :
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("sprite_sheet.plist");
_gameBatchNode = SpriteBatchNode::create("sprite_sheet.png");
this->addChild(_gameBatchNode, 1);
for animation :
auto animation = Animation::create();
int i;
for(i = 1; i <= 10; i++) {
auto name = String::createWithFormat("boom%i.png", i);
//auto name = String::createWithFormat("meteor-%i.png", i);
auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name->getCString());
animation->addSpriteFrame(frame);
}
animation->setDelayPerUnit(1 / 10.0f);
animation->setRestoreOriginalFrame(true);
note that boom.png & meteor.png is inside sprite_sheet.plist

Related

How to resize the the animating sprite in 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);

Flex string never cleared from the memory --> It is cleared eventually

I have this weird problem for a while and try to solve it to look up on the net for proper solution but still I am clueless.
When I check my application's memory usage with flex profiler (4.6) the portion of String keep increasing and eventually reach the point of crash.
And I pin pointed where this increasing occurs from my application's source code.
It is the local string variable that I passed to Json.decode(). It never cleared.
All the instance of the json string that I got from the socket server remains in the memory til app crashes even if profiler says there is 0 path to the String.
I don't know how to clear these Strings. It only keeps growing.
Please help me. I have been struggled with this for a week now.
Thanks for any support in advance.
portion of my source code that I think the source of the leak is as following.
protected function evtserverReseved(event:ProgressEvent):void{
var tmpArr:ByteArray = new ByteArray();
var tempByteArray:ByteArray = new ByteArray();
socEvtServer.readBytes(tmpArr, 0, socEvtServer.bytesAvailable);
tempByteArray.writeBytes(leftOverMessageNotify, 0, leftOverMessageNotify.length);
tempByteArray.writeBytes(tmpArr, 0, tmpArr.length);
leftOverMessageNotify = new ByteArray();
parseByteArray(tempByteArray);
}
private function parseByteArray(rawArray:ByteArray):void{
if(( rawArray[0] == 0x30 || rawArray[0] == 0x31 ) && rawArray[1] == 0x00 ){
var log:String = "";
for(var i:int=0; i<16; i++){
if(rawArray[i]==0){
}else{
log += rawArray[i]-48;
}
}
sizeOfFullListNotify = uint(log);
commonFunction.printLog("Event Server eventNotify sizeOfFullListNotify=" + sizeOfFullListNotify);
rawArray.position = 16;
}
var tempIdx:uint = rawArray.position;
var tempLength:uint = rawArray.length;
if(sizeOfFullListNotify <= tempLength - tempIdx){
var tempArray:ByteArray = new ByteArray();
var tempLeftOver:ByteArray = new ByteArray();
var j:uint;
for(j=0; j <sizeOfFullListNotify ; j++){
tempArray[j] = rawArray[j+tempIdx];
}
var euckrString:Object = tempArray.readMultiByte( tempArray.length,"euc-kr").replace(" ","").replace("\n","");
//commonFunction.printLog("Total memory=" + flash.system.System.totalMemory +", Free memory=" + flash.system.System.freeMemory + ", Event Server eventNotify JSON 수신 data size=" +euckrString.toString().length+ ", body=" + euckrString.toString() );
var ob:Object = com.adobe.serialization.json.JSON.decode(euckrString.toString());
commonFunction.printLog("Total memory=" + flash.system.System.totalMemory +", Free memory=" + flash.system.System.freeMemory + ", Event Server eventNotify JSON data size=" +euckrString.length+ ", body=" + euckrString );
if(ob.method != null){
//gridBox.DT_HOUSE.addItemAt(ob,0);
gridBox.DT_HOUSE.push(ob);
totlaReceivedList++;
}else if(!(ob.result is String)){
//confirm for registerEventNotify
commonFunction.printLog("confirm for registerEventNotify");
}
if(sizeOfFullListNotify < tempLength - tempIdx){
for(var k:uint=0; k <tempLength-tempIdx-sizeOfFullListNotify ; k++){
tempLeftOver[k] = rawArray[k+j+tempIdx];
}
parseByteArray(tempLeftOver);
}else{
//leftOverMessageNotify = new ByteArray();
}
}else{
//leftOverMessageNotify = rawArray;
for(var i:int = 0 ; i<rawArray.length ; i++){
leftOverMessageNotify[i] = rawArray[i];
}
rawArray = null;
}
}
var euckrString:Object(String) is the portion that never cleared from the memory.
It keeps stacking till crashes.

AS3: can't addchild indexed movieclips into a sprite

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();

Error #1009: Cannot access a property or method of a null object reference

I get the #1009 error while it visually works, can someone help me? Thanks in advance.
arrBellen is a Array on field-level.
private function bellenSpel(mv:MovieClip,x:Number):void{
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyHandler);
if(landschap.x == x){
mv.visible = true;
mv.mouseEnabled = true;
}
else{
mv.visible = false;
mv.mouseEnabled = false;
}
landschap.lblScore_onderwater.text.text = "Score: " + vogelTimer.currentCount;
if(vogelTimer.currentCount % 300 == 0) {
var bel:Bel = maakBellen();
arrBellen.push(bel);
}
for(var i = 0;arrBellen.length - 1;i++){
var bl:Bel = arrBellen[i];
bl.y += 2; // output says error is here
}
}
I think either your array isn't pospulated with the objects you think it is, or they can't cast to type Bel.
instead of:
var bel:Bel = maakBellen();
do like:
var bel:Bel = new maakBellen();
Okay here's my assumptions up front... A mgraph is right or maakBellen() is actually a function that returns an instance of Bel
you have an error in your loop condition you have:
for(var i = 0;arrBellen.length - 1;i++){
var bl:Bel = arrBellen[i];
bl.y += 2; // output says error is here
}
you should have
for(var i = 0;i < arrBellen.length;i++){
var bl:Bel = arrBellen[i];
bl.y += 2; // output says error is here
}
I'm a bit confused as to why this is causing a NPE rather than an OutOfRange type error.

Windows Azure: Argument Exception was unhandled

I want my Azure application to create a blob and write a data into it. When I tried it I got this exception stating that
ArgumentException was unhandled
Stream was not writable
here is my code
var ms = new MemoryStream();
for (int k = 0; k < 10; k++)
{
using (StreamWriter sw = new StreamWriter(ms))
{
string val = k.ToString();
if (k + 1 != len)
val = val + " ";
sw.Write(val);
sw.Flush();
}
}
ms.Position = 0;
blob.UploadFromStream(ms);
My code is getting executed for k = 0. The exception is thrown when k = 1.
Can anyone tell me how to solve this exception
Moreover, Is this the correct procedure for writing onto the blob. If no, where am I went wrong and how to correct it.
My guess is that the Finalize method of StreamWriter closes the underlying stream (so next time through the loop, you can't write to that MemoryStream).
I think you can solve this by puting the "using (StreamWriter sw = new StreamWriter(ms))" block around the whole loop. It's presumably more efficient than creating a new StreamWriter each time anyway.
In any case, if you're just writing text, it might be better to do something like:
StringBuilder sb = new StringBuilder();
for (int k = 0; k < 10; k++)
{
sb.Append(k.ToString());
if (k + 1 != len) sb.Append(" ");
}
blob.UploadText(sb.ToString());
Or (for this particular use), get fancy. :-) (completely untested):
blob.UploadText(string.Join(" ", Enumerable.Range(0, 10).Select(k => k.ToString()).ToArray()));