Remove child from Batch node one after another with a pause - cocos2d-x

I am trying to remove a set of children from the batch node one by one after some pause . So if three children are there, then firstly parent will disappear immidiatley , then after 1 second first child will disappear, then after another 1 second(total 2 seconds) 2nd child will disappear and after another 1 second(total 3 seconds) third child will disappear.
Right now I am removing them from the batchnode like :-
batchNode->removeChild(child1,true);
sleep(1);
batchNode->removeChild(child2,true);
sleep(2)
batchNode->removeChild(child3,true);
But they all disappear from screen at same time ! although pause is there. Is it because they all are part of same batchNode so any action taken on children will be applied at one go. ?
Please share your thoughts

ie, they all disappear together after 3 seconds ? Basically, i think that the sleep is actually blocking the main thread, so the update & draw cycle will only resume after the last one of your statements.
I would do something like that by running some kind of CCSequence , with delay actions and callBlock actions to cascade properly. This is all executed within the main thread, so the display will be refreshed during the cascade.

Sleep() argument is typically measured in milliseconds, so try sleep(1000); in second and fourth lines.
Also, maybe, you'd better to use Actions (CCSequence stuffed with CCDelay and CCCallFunc) instead of sleep() which blocks all your game.

I am able to do it , I used two different ways as described:-
1> By postponing the removal of subsequent children in further frames.
2> or instead of depending on the frames, I used delta time (time since the last frame was drawn).So remove a child only after say 0.5 secs.
Using either of the above way , I can omit the use of sleep which can hog my main thread.
Here are the details, considering I have in total three children to remove:-
1> By postponing the removal of subsequent children in further frames.
In the current frame I will remove first child then will set a flag to notify in the Update not to do anything but wait for say 15 frames, while waiting 15 frames I can do other tasks also which doesnot have impact on gameplay
Although with this I have flexibility to wait for any number of frames, but I will have to regulate the frame rate for different devices, as in slow devices, waiting 15 frames can take more time than fast device, and I am not able to know if cocos2dx does regulate the frame rate itself, so I quickly jumped to next solution.
2> or instead of depending on the frames, I used delta time (time since the last frame was drawn).So remove a child only after say 0.5 secs.
Here instead of waiting 15 frames I used following condition inside Update(float dt):-
if(gameState==WaitForNextChildRemoval)
{
deltaTime=deltaTime+dt;
if(deltaTime>=0.5)
{
releaseNextChild();
deltaTime=0;
}
}
here irrespective of the device(slow or fast), next child will be removed after 0.5 secs.
One improvement I think should be made is when deltaTime becomes more than say 1 sec , and then instead of removing only next one child, it should remove two children (0.5 secs for each) at one go , as player is expecting to remove one child after 0.5 secs so deltaTime being 1 sec(approx), I should balance this expectation.
Please share your thoughts.

Related

as3 - how to randomize object positions without colliding?

If I have two instances called block1 and block2. And they move off the stage. It scrolls down the y position and it respawns back on top. But I don't want the x/y position colliding with the other blocks? I want it to respawn back to position, but I want it randomized but at the same time I don't want it touching each other?
Heres my code:
if (block1.y > stage.stageHeight)
{
block1.y = -550;
block1.x = (Math.floor(Math.random() * (maxNum - minNum + 5)) + minNum);
}
I'm pretty sure I'm calculating the respawn coordinates the wrong way, but I'm not sure how to put it in a random x and y position without colliding with other blocks.
A very simple method can be just to spawn your box, do a collision check, then if collision, remove and respawn and recheck until you find an empty spot where it fits
This is obviously quite inefficient, but is pretty simple to implement quickly if you have some sort of collision detection already working. Keep in mind if there is no spot that it can fit in, then it'll loop forever so you may want to set a max try count or something of that sort.
How fast/well it'll actually work will depend on if the spawn area is pretty sparse or pretty dense, which will increase/decrease the percentage that it'll find a good empty spot the first few times.
There is some room for improvement, going down this path though, such as if your collision detection system gives a minimum translation vector, you could just move the new shape over and use that position to spawn.
Other simple methods could involve keeping track of known occupied positions and adjusting your random range to avoid those values.

Collision Detection - Ordering - Which collision goes first?

So I am making a physics engine that only uses rectangles (axis-aligned bounding boxes) as shapes. I have implemented a method from christer ericsons book that returns the collision time and normal of two moving aabbs. I also have made another method that takes two aabbs velocities, positions and a normal that responds to the collision and give the aabbs new velocities.
The actual problem now is is that I don't know how the loop, that checks the collisions between all aabbs and responds to them, should look like. Simply I don't understand how to order the collisions by the time of impact, and which collision I should respond to.
A loop written in pseudo code that shows how to order all collisions would be really helpful.
Another thing I've mentioned is that it's possible thata moving box could bounce between two static boxes hundreds of times in a single frame if it's velocity is really high, how do you handle that?
You should let a simple priority queue take care of the right order of execution. Conceptually, this would end up looking something like this:
queue<CollisionEvent> q = new empty queue
while (!q.isEmpty) {
nextCollision = q.dequeueMinimum
/* run animation until nextCollision.time
...
*/
newMovingParticles = nextCollision.movingParticles
newCollisions = computeCollisionEvents(newMovingParticles, allOtherParticles);
for each event in newCollisions {
q.enqueue(event, event.time);
}
}
What about boxes that move with large velocities: I don't know. Physically, it would make sense to just accept that it can happen that there is a sequence of very frequent collision events. I can not explain why, but for some reason I do not expect any infinite loops or zeno-type-problems. I would rather expect that even frontal collisions of very heavy boxes with very light boxes, where the light box is trapped between the heavy box and the wall, end in finitely many steps. This is what makes the rigid bodies rigid, I think one should just accept this as a feature.

Pygame: Test if entity collides with another of itself?

So I am working on a tiny little 2d voxxel game in Pygame, and I want the blocks that you place to be gravity affected, but in order to do this.. I need an entity to be able to collide "with itself" (as in another one of itself). Here is the collision code:
for block in blocklist:
if block.rect.colliderect(block.rect):
exit()
exit() is just to verify when the event returns positive, but unfortunately, whenever I create one block... it detects the collision with itself and exits.
What can I do to get around this?
Thanks!
-Sam
Your example just checks the first block in your list against itself - it's always going to collide.
You want to test each block in the list, against every other block in the list:
for block in blocklist:
if any(block.rect.colliderect(x.rect) for x in blocklist if x is not block):
exit()

Gradually rotate towards a direction

I have a car object, and I want it to gradually rotate to the direction where the user clicked.
Every frame I did math to calculate the new direction it needs, and it's stored at car.direction. The actual direction is of course in car.rotation.
Now I want to update the rotation every frame until it's equal to the direction. However I tried everything and can't figure out how to do that.
By the way, I'm using FireFly, that is a gameengine built on top of Starling Framework, But I don't think it's relevant.
I would go with Marty's suggestion, use the smallestAngle function to determine which direction you should be rotating. Basically you can move some percentage of the smallestAngle during every frame update until the percentage of that smallestAngle is below some threshold (and have it "snap" the rest of the way).
Something like
//each time this is called it will get 1/4 closer, but never get to 0, hence the need for a threshold avoid paradoxes
//http://en.wikipedia.org/wiki/Zeno's_paradoxes#Dichotomy_paradox
var angleToMove:Number = smallestAngle()/4; //the divide by 4 here means get 1/4 of the angle gap closer each time this function is called, I assume this is on a timer or frame handler, making the 4 greater will make it follow more slowly, making it lower will make it follow more quickly, never reduce to or below 0 unless you want wonkiness
if(angleToMove<someRadianThreshold)
angleToMove = smallestAngle();
//use angleToMove to adjust the current heading/rotation

Infinite horizontal scroll at constant speed in AS3 using TweenLite

I need to do an endless horizontal scroll of elements within a parent MovieClip.
No matter what ever method I try, an element of 'drift' occurs and eventually the elements start to overlap.
I've tried using relative recursive tweening for each element according
but this method seems prone to quite a bit of error after repeated starts and stops.
//CODE START
function doScroll():void {
TweenLite.to(this, .25, {x:"20", ease:Linear.easeNone,onUpdate:checkPos,onComplete:doScroll});
}
//CODE END
I've reverted to doing absolute tweens to a predefined position using a contant speed. This seems to be more accurate but still some 'drift' occurs.
//CODE START
//_dest is predefined
var speed:Number = 500;
var dist:Number = this.x - _dest;
var distAbs:Number = dist < 0 ? -dist : dist;
//kludge to get constant velocity by recalculating time every frame
_time = distAbs / speed;
TweenLite.to(this, _time, {x:_dest, ease:Linear.easeNone,onComplete:reset});
//CODE END
Thought this should be very simple.
Can anyone point me to any possible tutorials or make any suggestions?
Any help appreciated.
Solution/Discussion at http://forums.greensock.com/viewtopic.php?f=1&t=6800
(warning: this is gonna require a rather lengthy explanation...)
It's a logic problem in your code. In your onUpdate, you were running conditional logic such that if the x position is beyond 980, it kills the tween and moves x back to -980 and starts things over. You're doing that for each individual item, each of which begins at a different position. That initial position affects when it crosses that threshold, thus when they reposition, the offsets are different.
For example, let's say item1 starts at an x position of 0 and item2 starts at 490 and both start moving at 400 pixels per second and your frame rate is 60, thus they'll move 6.66666 pixels per frame. Item1 will take 147 frames to hit 980. However, item2 will take 74 frames (actually 73.5, but there's no such thing as a half-frame) to cross the 980 threshold, but when it does so it will be at an x position of 983.333333. At that point it jumps back to -980 due to your conditional logic, but notice that it traveled an EXTRA 3.333333 pixels. You intended Item1 and item2 to travel at the exact same velocities and they do during the tween, but your onUpdate logic is misaligning them on the reposition such that in the end, some are traveling more than others which affects their overall velocity.
Another issue has to do with the fact that Flash rounds x/y coordinates of DisplayObjects to the nearest 0.05. So when you do your manual reposition (wrap), small rounding errors creep in. For example, let's say TweenLite sets the exact x value to 980.799. Flash will actually round that to 980.75. Then when you reposition it like this.x -= 980 and then tween it, the value would have just lost almost 0.05 pixels on that round. Do that many times and it can add up to a half-pixel or whole pixel (or more). All your items are crossing the threshold at slightly different spots, thus the rounding errors aren't the same, thus you start seeing slight variances in the spacing. Again, this is NOT an issue with the tweening engine. You'll see that the engine itself sets the values correctly, but Flash rounds them internally when applied to DisplayObjects.
A solution was posted at http://forums.greensock.com/viewtopic.php?f=1&t=6800 that includes an FLA and support files.
As others have suggested, I'd recommend having a single chunk of code that manages ALL the items that you're aligning/scrolling. It would lay things out from a single reference point so that everything lines up perfectly every time. You could tween a getter/setter that applies the logic. I use that technique all the time and it works great. You can see a smaller-scale example in the code I attached in the above URL (the scrollX getter/setter in ItemBase.as)
If you will be tweening all background elements at the same rate indefinitely on a single dimension - why not use a Timer and bypass tweening libraries entirely?