How to attach an image to a moving Sprite?

I have a Sprite that currently moves around on the screen, and I have made it interactive, so it can receive click events.

Now, in my onSpriteClicked(sprite, x, y) callback, I would like to add a red dot to the sprite (at x,y).

If I call this.add.circle(x,y, 10, 0xff0000) it adds the dot but, predictably, it doesn’t stick to the sprite. So how can I make the dot stick to the sprite so it moves around with it?

Cheers,
Jim

:wave:

Use a container instead, or update the dot position manually.

Hiya Samme, Can you point me in the right direction re containers? (Am brand new to Phaser!)

Here’s an example how you can add dot to container:

You have to remember that container’s children positions are relative to their parent container.

//add dot to container on clicking on it
container.on('pointerdown', function (pointer) {
    //set dot coordinates relative to container
    let x = pointer.position.x - container.x,
        y = pointer.position.y - container.y,
        dot = scene.add.circle(x, y, 10, 0xff0000);

    //add dot to container
    this.add(dot);
});
2 Likes

Thanks wiserim! Thought your code wasn’t working at first - had to scroll to get the green square into view. Looks like just what I need though, thanks very much. :sunny:

I just have one more question regarding the above example: How would I make it so when you click near the edge of the green square, the red dot is clipped (ie, so the only part of the red dot that shows is the part that is overlapping the green square)?

It seems at the moment that the red dot is able to increase the size of the container.

(Also, I’ll be using a sprite rather than a circle - just in case that makes any difference.)

Use a rectangular geometry mask on the container. You’ll have to move the mask source (graphics) with the container.

Thanks, samme.

I found this - Phaser.Display.Masks.GeometryMask - Phaser 3 API Documentation (beta) - but no idea how to use it.

In my case, instead of the green square in the above example, I have a sprite. The sprite contains transparent and non-transparent pixels, so maybe I can use that as the mask somehow?

There are some v3.55 geometry mask examples, they will work the same in v3.60.