Stop Matter mouseSpring to apply force on pointer up immediately (drag-end)


#1

I have a bit special case: a sprite is moved by a matter mouseSpring. Works fine.

I have to simulate magnetic attraction while holding/moving the sprite. Means the sprite moves a bit in the direction of another object (magnet)
This is done in scene.update() by manipulation sprite x/y towards the magnet. Just a bit. The effect works as expected.

The problems begins when you release the mouse button (drag-end). Then the mouse spring force is applied by matter. The sprite is pulled back in direction to the mouse position (like a spring would do). This is kind of the expected behaviour, but I would like to stay the sprite on it’s position (which is a bit away from the mouse pointer).

I tried many events from phaser and matter (dragend, beforeupdate, step, beforestep) to stop that, but I can’t force matter to let that sprite stay where it is.
I also call this.matter.step() instead of autoUpdate to get some control.

sprite.setVelocity(0,0) in some of the event hooks helped a bit, but still there’s a bit movement.

Is there a event/hook I should use, or how can I force matter to stop the connection between the mouse spring and the sprite?

Any ideas are welcome


#2

I couldn’t find a solution for the problem, but I think the following code provides a better solution for the wanted magnetic attraction anyway.

What it does is using offset variables which is added to x/y right before the rendering and after rendering the position is reverted.

The result is that the sprite is drawn to an offset position while everything works like the sprite is at it’s original position.

export class Player extends Phaser.Physics.Matter.Sprite {

  protected offsetX: number = 0;
  protected offsetY: number = 0;

  constructor(scene: Phaser.Scene, x: number, y: number, texture: string, frame?: string | integer, options?: object) {
    super(scene.matter.world, x, y, texture, frame);
    scene.matter.world.add(this);
    scene.sys.displayList.add(this);
    scene.sys.updateList.add(this);
  }
  
  // setting this.offsetY/X shifts the rendering of the sprite to another position
    
  renderCanvas(renderer: any, src: Phaser.GameObjects.Sprite, interpolationPercentage: any, camera: any, parentMatrix: any) {
    src.x += this.offsetX;
    src.y += this.offsetY;
    renderer.batchSprite(src, src.frame, camera, parentMatrix);
    src.x -= this.offsetX;
    src.y -= this.offsetY;
  };
}

#3

Have you tried:

mySprite.on('pointerup', function(){
    mySprite.setStatic(true);
});

Also, make sure your sprite is set to mySprite.setInteractive();