javascriptjsonphaser-framework

Is there any way i can get both Matter and Arcade physic in Player object


I tried to create a player object

export default class Player extends Phaser.Physics.Matter.Sprite {
    constructor(data) {
        let { scene, x, y, texture, frame } = data;
        super(scene.matter.world, x, y, texture, frame);
        this.scene.add.existing(this);
        

But then i need to move my character by mouse, not dragging him. Is there any solution for this?


Solution

  • I'm not sure if this is what you are looking for, but if you only want to moteh the object to the click position.
    You can simply use phaser vectors (link to documentation) to create and calculate a new direction and Velocity.

    Here a small Demo:

    document.body.style = 'margin:0;';
    
    var config = { 
        width: 536,
        height: 183,
        physics: {
            default: 'matter',
            matter: {
                gravity: { y: 0 }, 
                debug: true
            }
        },
        scene: { create, update }, 
    }; 
    
    function create () {
        this.add.text(10,10, 'Click to move object')
            .setScale(1.5)
            .setOrigin(0)
            .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
    
        let graphics  = this.make.graphics();
        graphics.fillStyle(0xffffff);
        graphics.fillRect(0, 0, 20, 20);
        graphics.generateTexture('img', 20, 20);
        
        this.player = this.matter.add.image(250, 90, 'img', { restitution: 0.9 });
        this.input.on('pointerdown', moveToPoint, this);
        
        // Some objects to collide
        
        for(let idx = 0; idx < 5; idx++){
            this.matter.add.rectangle(400, 30 + 30 *idx, 10, 10, { restitution: 0.9 });
        }
        
    }
    
    function moveToPoint({x, y}){
    
        // Save WayPoint
        this.wayPoint = new Phaser.Math.Vector2( x, y );  
        let newVelocity = this.wayPoint
          .clone()
          .subtract(this.player)
          .setLength(10);
        
        this.player.setVelocity( newVelocity.x, newVelocity.y );
    }
    
    function update(){
       if(this.wayPoint){
           // check if near to waypoint, to prevent pass
           if(this.wayPoint.distance(this.player) <=  10){
              // clear waypoint
              this.wayPoint = null;
              this.player.setVelocity(0);
           }
       }
    }
    
    new Phaser.Game(config);
    console.clear();
    <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>