Custom collider for Arcade physics

With the following code, we can detect collisions between the player and the game platforms:

this.physics.add.collider(this.player, this.platforms);

The problem is, Phaser uses the bounding box of the sprite to detect collisions:

hitbox1

But I would like to detect collisions only on single pixels like so:

hitbox2

How should I do?

You can get some help here -
https://rexrainbow.github.io/phaser3-rex-notes/docs/site/arcade-body/#collision-bound
Set the width and height to 1 and the center to the center of sprite.

Thank you, but how can I add 3 more pixels for collision at other positions?

What physics engine are you using?

Arcade

Arcade Physics, 1 sprite with multiple colliders
Maybe this can help

Do you want to check every pixel on the character or just 4 points?

Just 4 pixels.

What I have tried to do so far is to create 2 physics groups for the player:

  • The first one contains the sprite and the collision pixels (that are only rectangles of 1x1 of size). This is the group that I use when I want to move the player, because all its components move together (the sprite and the pixels). This group shouldn’t have any collider.
  • The second one consists of only the collision pixels, and it has a collider with the platforms.

So I tried to create the first group (that I call player) containing the sprite and the pixels, and I gave it a collider just for testing:

this.player = this.physics.add.group();
const sprite = this.add.sprite(...);
// rectangles of only 1 pixel
const bottomPixel = this.add.rectangle(...);
const leftPixel = this.add.rectangle(...);
const rightPixel = this.add.rectangle(...);
this.player.addMultiple([sprite, bottomPixel, leftPixel, rightPixel]);
this.physics.add.collider(this.player, this.platforms);

forto-hitbox3

The problem is that all the components are individually subject to gravity and they fall down, but I would like the collision pixels to stay fixed like in the first picture (even though I would like the general structure i.e. the player group to be subject to gravity). Preferably, I would like a solution that doesn’t involve repositioning the components for each frame.

You can disable gravity for the “pixel” bodies.

I already tried but the pixels floated and didn’t move along with the sprite.

I think you will have to reposition the components somehow. You could use a Container, but I’m not sure bodies inside it would work right.

You can detect collisions like this

but that wouldn’t give the kind of separation (blocking, bouncing) you want. You would have to add a custom separation method.

I think you can adapt Compound bodies … if you use tiny rectangles.