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?
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);
});
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.
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.)
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?