I am making a game where every time you click, a fruit falls down from the mouse coordinates. The game was working when I was working with plain colours, so then I decided to add textures. However, I encountered two issues.
- I have to manually add in
xScale
andyScale
, which isn’t good since there are many different fruits and sizes and I don’t want to manually tune it for all of them. I tried to get the size of the body and divide it by the image size. My code is below:
// getting the size of the fruit by the type of fruit it is
radius = fruit_kinds.indexOf(kind)*6+10
// making the fruit, note that I already defined mouse_x before
fruit = Bodies.circle(mouse_x, 120, radius, { isStatic: false })
// getting the image
const path = '../static/assets/cherry.png';
const image = new Image();
image.src = path;
// getting the scales (this might not work).
// Note that 2*radius = diameter = width of fruit
xscale = 2*radius/(image.width)
yscale = 2*radius/(image.height)
// adding it to the body parameters
fruit['render']['sprite']['texture'] = path
fruit['render']['sprite']['xScale'] = xscale
fruit['render']['sprite']['yScale'] = yscale
When I ran this code, the sprite became so small that I could barely see it. I suspect that the radius isn’t in the same units as the image size I got? But I am not sure. Help would be appreciated!
- The sprite I added was not appearing directly on the body. There seems to be some offset. I thought that the offset was due to
xOffset
andyOffset
, so I made them zero.
fruit['render']['sprite']['xOffset'] = 0
fruit['render']['sprite']['yOffset'] = 0
However, when I tried this, the fruit disappeared.
I have checked many other StackOverflow posts, however none of these can help with my problem.
- Sprite image not appearing on matter.js The image is appearing, just not the right size and not the right place.
- How to apply sprite textures to matter.js bodies Again, the image is appearing for me. Also, I am not using a canvas, not even a div element. Would that be a bad thing?
- Matter.Js scaling a sprite (related to other variables) That question regards expression
xScale
in terms of other variables, but I want to automatically findxScale
such that it covers the whole body almost perfectly.
Could somebody please help? Thank you in advance 😀