Is it possible to incorporate both Matter and Arcade physics into the Player object?

I attempted to instantiate 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);
        

However, I now require a way to move my character using the mouse, rather than dragging. Is there a solution for this?

Answer №1

If you're unsure whether this meets your needs, here's a solution for moving an object to the click position using Phaser vectors. To achieve this, you can refer to the Phaser.Math.Vector2 documentation for creating and calculating a new direction and velocity.

Check out a quick demo below:

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);
    
    // Additional objects for collision
    
    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 overshooting
       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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to make the primary button on the previous page function correctly again, just like it did before it was clicked?

Issue Description: I am facing an issue on the order page where I need to link the "Continue" button to a booking page. After reaching the booking page, I expect users to be able to navigate between the two pages seamlessly even when they use the browser& ...

Using Node.js, Socket.IO, and Express to deliver static JavaScript files served dynamically

I have been working on a node.js application that utilizes socket.io and express. Initially, all of the javascript was included in the HTML file, but now I am looking to separate it into a .js file. In my primary node application, this is what I currently ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but I’m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Incorporate titles for items in the jquery caroufredsel plugin

I am currently using the second example of the caroufredsel plugin, which can be found on this page . I am attempting to add a caption for each picture. To achieve this, I have used `li` and `lis` in my HTML code: <div class="list_carousel"> &l ...

Working with arrays of objects in D3.js using Javascript

Seeking guidance as I navigate through the world of javascript and D3.js. I have two distinct data sets (arrays of objects) that I hope to merge. My goal is to align the National Average Scores with the State Average Scores by matching the 'Answer&ap ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Hide the drawer when a user clicks on a currently selected tab

Just starting to explore Material-UI and React here, so please bear with me if I'm making any rookie mistakes. :) I've set up a Drawer component containing a Tabs element with multiple Tab components inside. It's nothing too fancy yet - mos ...

What is the best way to split an AJAX response into different variables and effectively retrieve each one of them?

When using AJAX to fetch data from a database and display it in a text box, most examples found online only show how to display the AJAX response in one text box. But what if we need to separate multiple PHP variables retrieved from the AJAX response and d ...

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

Refreshing the page triggers the callback function that retrieves the checkboxes selected in a Kendo treeview component

How can I retain the selected checkboxes after refreshing the page? Is there a way to achieve this using AJAX when submitting data to a database and then reloading the page? AJAX //AJAX call for button $("#primaryTextButton").kendoButton(); va ...

Easily implement a wide variety of fonts in your web projects by dynamically loading hundreds of font

I am in possession of a directory called /assets/fonts containing a plethora of fonts that I wish to incorporate into a website in a dynamic manner. Users will be able to specify their font preferences, akin to a text editor. Individually assigning the fo ...

From organizing nested arrays in jSon to visualizing data with D3js

I am completely new to working with d3 and JSON. I have a piece of data from JSON that I am attempting to extract, and I'm wondering if I am headed in the right direction. My goal is to display a rectangle graph for each server within different statu ...

Color Your Plone Website with a Custom JavaScript Colorscheme

Currently, I have implemented a custom theme by registering the javascript in the skin.xml file and then creating a specific folder within the browser to store the script. Below is the script shared by one of the users: $(document).ready(function(){ ...

The play button in videojs is unresponsive when incorporated into JavaScript responses

I've been trying to implement a video player using video.js, but I'm running into issues with the play button not responding to my JavaScript code. I have all the necessary scripts included in my file, but I haven't been able to find a solut ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Ways to develop tests for functions specific to my scenario

Currently, I am attempting to implement a timeout function test within my application. Within the controller: $scope.$watch('toy',function(toyVar){ if(toyVar == 1) { //perform actions } else { $timeout(f ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...