How to scale an image to exactly fit a body?

General discussion about the R.U.B.E editor
Post Reply
bvargish
Posts: 26
Joined: Fri Oct 02, 2015 4:17 pm

How to scale an image to exactly fit a body?

Post by bvargish »

I apologize if this has already been answered, but the forum keeps telling me "The following words in your search query were ignored because they are too common words" no matter what I put!

Suppose I have a scene that contains a bunch of circular bodies at different sizes and I'd like to use one image of a beach ball for every body. I duplicate and attach this image to each body and need to size it to match the body's size. Is there an easy way to do this? I'd also like to do this for square bodies.

I'm also curious whether this could be done from within Phaser after loading in my R.U.B.E. world. I would need to be able to detect the width of a body which has now been translated to pixels on the screen, size the sprite image accordingly and then attach it to the body. I looked into this but didn't have any luck.
iforce2d
Site Admin
Posts: 861
Joined: Sat Dec 22, 2012 7:20 pm

Re: How to scale an image to exactly fit a body?

Post by iforce2d »

One way might be to make one ball first, with image attached, and then duplicate that and scale it as needed. From our other discussion though I guess you'll already have the bodies in place and you just need to attach images, so duplicating to make the bodies is probably not an option.

If the sizes of the balls are known, you could perhaps set one up first, and copy that image to all the others (select the image and copy, then select all the bodies you want it to go on and paste). Then you would need to manually multiply the 'scale' property of each image to: ballSize / templateBallSize. You could also make a script that gets the radius of the fixture of each body to automate this, if you need to do it for multiple levels/scenes. I'll leave that to you for now, but if you need a hand just let me know. Here are some tips:
- the body class has getImages() and getFixtures() functions
- the fixture class has a getShapes() function
- the shape class has getRadius()/setRadius() functions, and a 'type' member (which will be zero for circles)
You could get the template body by name (getBody(string)) and the image scale and fixture size. Then perhaps loop over all selected bodies to set the scale of the image as appropriate. It sounds like there will just be one fixture and one image on each of these bodies, if so then you can do getImages()[0] and getFixtures()[0] as shorthand to get just that single item.
bvargish
Posts: 26
Joined: Fri Oct 02, 2015 4:17 pm

Re: How to scale an image to exactly fit a body?

Post by bvargish »

Thanks for all the pointers! So far I've been having success with scripts to size and position elements so I should be able to pull this off.
Post Reply