How to safely destroy() a sprite with a physics body?

Recommended Posts

Hi all,


I know this has been asked before, but I still couldn't get any clarity after reading those other posts.


Every time I try to destroy an object when it passes out of bounds I get an error, usually:


Uncaught TypeError: Cannot read property 'camera' of null


I understand that I'm probably trying to do something with that object when it is already destroyed... the problem is I don't know what. The object is in a group which is being checked for collisions against another group. It also has a physics body. I've tried removing the object from its group before destroying it, but still no dice.


Any guidance is appreciated -



Share this post

Link to post
Share on other sites

Adam's correct with one exception:


For a sprite to kill itself when it goes out of bounds:

var sprite = game.add.sprite(100,100,'sprite');sprite.checkWorldBounds = true;// checkWorldBounds must be enabled for a sprite to kill itself// when it goes out of bounds.// This causes the sprite to check it's position every frame.// It can be expensive, especially if you have a metric buttload of// sprites doing this.sprite.outOfBoundsKill = true;// this will automatically have the sprite call it's own "kill()" method // if it leaves the world bounds.

Share this post

Link to post
Share on other sites

Hi guys,


Thanks for your replies - I have this working but I was concerned with 'killing' the sprites as opposed to destroying them. Since I'm not reusing sprites (I'm creating new ones at set intervals) I was hoping to avoid a memory buildup of undrawn, "killed" sprites. Does anyone know if this is a valid concern or not?


Thanks again  -

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.