Quantcast
Channel: Cocos Forums - Latest topics
Viewing all articles
Browse latest Browse all 17126

How to detect when a node is removed?

$
0
0

@kingchimp wrote:

Hello all,

I am developing a game that's loosely based on the classic asteroids arcade game. As part of this, I have a battleship object that cruises around the asteroid field and has a couple of gun turrets on it. Every second or so, the turrets find the nearest asteroid and start turning towards it, firing the gun. This obviously requires some calculation every frame, so that the turret can stay on target. At present, the code to orient the turret at the target is in the turret class' update() method, scheduled 60 times per second.

The problem I'm having is that when the asteroid is destroyed (by the player or the battleship, or something else), the turret will keep trying to aim at it every 1/60th of a second. As soon as the asteroid node is removed from the scene (as soon as it's destroyed in this case), the function fails with an invalid memory address because it's still trying to access the asteroid's position for its calculations.

I tried to get round this by doing this every time the turret updates, to check whether the target is still a valid member of the scene. The aiming code comes straight after it:

if (this->getParent()->getChildren().getIndex(_target) == UINT_MAX)
{
_isEngaged = false;
return;
}

Unfortunately it still crashes sometimes, I think when the asteroid is destroyed and removed from the scene in the instant between this check and the aiming code being run, it fails.

So, does anyone know a good way to fix this? I might well be approaching the problem all wrong...

Thanks in advance!

Posts: 3

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 17126

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>