Jump to content

Box2D plugin: how can I attach sprite to existing body?


Go to solution Solved by kleepklep,

Recommended Posts

  • Solution

Ha, I didn't think to try it the other way around! Thanks!

It turns out that you have to define both the body's sprite and the sprite's body to get this to work.

var bridgeSprite = game.add.sprite(0, 0, 'log');bridgeSprite.anchor.setTo(0.5, 0.5);bridgeBody.sprite = bridgeSprite;bridgeSprite.body = bridgeBody;
Note that if you do this and are using phaser-rube.js's removeBodyAndSprites function that the sprite would stick around. So you'd need to use body.sprite.destroy() to get rid of it.
Link to post
Share on other sites

Here's the code I'm using to add images to my R.U.B.E scene in Phaser rather than in R.U.B.E, which worked better for my purposes. I right clicked in R.U.B.E.'s properties panel, added a new custom property called img (set to string) and I'm linking an image to a body if the property is defined. Alternately, you could use the body names as image names (they don't all have to be different) instead of a custom variable, but I was already using it for something else. If all of your images are defined outside of R.U.B.E. you won't need to call updateRubeSprites() in Phaser's update function. Hope someone finds this is helpful!

 

// add images to RUBE generated bodiesfunction addImages(){	for (var i = 0; i < levelScene.bodies.length; i++) {		var n = levelScene.bodies[i].name;		var b = levelScene.getBody(n); // levelScene.bodies[i] breaks		if (b.data.customProperties) {			var img = getProp(b, 'img');			if (img){				console.log(i, b.name, img);				var s = game.add.sprite(0, 0, img);				s.anchor.setTo(0.5, 0.5);				b.sprite = s;				s.body = b;			}		}	}}// get custom properties from RUBE generated bodiesfunction getProp(body, key) {	var arr = body.data.customProperties;	for (var i = 0; i < arr.length; i++) {		//console.log(arr[i]);		if (arr[i].name == key) {			//console.log(arr[i].int);			if (arr[i].int) {				return arr[i].int;			} else if (arr[i].string) {				return arr[i].string;			}		}	}}
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.

Guest
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.

Loading...
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...