How do I render a cropped piece of an image

I have an image (wall.png) that’s 600x600 px. I want to write a function that draws a cropped version onto the screen at the given x and y coordinates, and the given width and height.

Here is my code:

function add_wall(x:number, y:number, width:number, height:number, scene:Phaser.Scene){
	var wall_obj = scene.physics.add.image(x,y ,"wall"); 
	wall_obj.setCrop(0,0,width,height);
        wall_obj.setSize(width, height);
	wall_obj.setDisplaySize(width, height);
	wall_obj.setPosition(x,y);
	scene.data.get("walls").add(wall_obj);
}

It draws the walls at the correct locations, but the sizes are all messed up - a 100x100 image is resized to around 18x18

If I remove the setDisplaySize as follows:

function add_wall(x:number, y:number, width:number, height:number, scene:Phaser.Scene){
	var wall_obj = scene.physics.add.image(x,y ,"wall"); 
	wall_obj.setCrop(0,0,width,height);
        wall_obj.setSize(width, height);
//	wall_obj.setDisplaySize(width, height);
	wall_obj.setPosition(x,y);
	scene.data.get("walls").add(wall_obj);
}

The image is added with the correct size, but the location is wrong, it’s further up and to the left than it’s supposed to.

How do I add it properly?

EDIT: I managed to get it to work with the following:

function add_wall(x:number, y:number, width:number, height:number, scene:Phaser.Scene){
	var wall_obj = scene.physics.add.image(0,0 ,"wall"); 
	wall_obj.setCrop(0,0,width, height);
	wall_obj.setDisplayOrigin(0,0);
	wall_obj.setSize(width, height);
	wall_obj.setPosition(x, y);
	scene.data.get("walls").add(wall_obj);
}

But now the colliders are in the wrong location. How do I make the collider go to on top of the image?

:wave:

function add_wall(x: number, y: number, width: number, height: number, scene: Phaser.Scene) {
  var wall_obj = scene.physics.add.image(x, y, "wall").setOrigin(0, 0);

  wall_obj.setCrop(0, 0, width, height);
  wall_obj.body.setSize(width, height, false);

  scene.data.get("walls").add(wall_obj);
}

Thank you, it works.
Also, what does the “false” in wall_obj.body.setSize(width, height, false); do? The documentation says " Modify the Body’s offset , placing the Body’s center on its Game Object’s center" which I don’t understand. What’s the difference between a “Body” and a “Game Object”?

The body is the physics body attached to the game object (image). It defines the shape used for physics collisions, which is what you see in the Arcade Physics debug display. The body offset is the distance from the top-left of the game object to the top-left of the body.

Since you’re cropping at (0, 0) you want a body offset of (0, 0) also.