Tutorial on moving a bullet towards the cursor in Phaser 3

Currently, I am working on developing a 2D game and facing a challenge in making the bullets move towards the cursor. Here is the code snippet that I have been using:

let xDist = this.game.input.mousePointer.x - this.x;
let yDist = this.game.input.mousePointer.y - this.y;
let angle = Math.atan(yDist / xDist);

this.projectile_sprite.setVelocityX(yDist);
this.projectile_sprite.setVelocityY(xDist);

I have noticed that the projectile moves faster when it is further away from the cursor, which is not the intended behavior. Can you suggest a solution to fix this issue?

Answer №1

When working in Phaser, velocity refers to the speed at which an object moves towards a specific point. By setting the velocity of your projectile based on the distance between the object and the cursor, you ensure that it will move faster when the cursor is further away.

To achieve this, you need to determine the cursor's position and then direct your projectile towards that location. Assuming you are utilizing a built-in physics library with methods like setVelocityX(), the process can be simplified as follows:

this.physics.moveTo(this.projectile_sprite, this.game.input.mousePointer.x,
  this.game.input.mousePointer.y);

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

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...

Using JQuery with ASP.NET buttons

I am having trouble getting a jQuery function to fire in an ASP.NET button. It doesn't seem to be triggering. What could be the issue? //Code <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type= ...

How to utilize a prepared statement in MySQL using NodeJS for inserting or updating data in a specific table?

Below is the code snippet I need assistance with: connection.query({ sql: 'CREATE TABLE ? ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday`) ENGINE = InnoDB ...

A step-by-step guide on generating a dynamic JSON file with JavaScript

I am in need of generating a JSON structure that follows this specific format: {"content": { "properties": { "area_id": "20", "origin": "3", "axis": "1", "x_start": "00", "x_end": "99", "y_start": "00", ...

What could be causing the ReferenceError when the Response object is not defined?

I am currently working on node.js and express. After attempting to establish a simple server, I am encountering an unexpected response error. const http = require('http'); const myServer = http.createServer(function(req, res){ res.writeHead ...

Node.js server experiences a crash after attempting to send a large string using res.send()

I've recently started learning JavaScript and NodeJs. I'm facing an issue with my Nodejs application crashing when a get request is made, specifically when trying to return a large string. app.mjs app.get('/log', function (req, res) { ...

Old information gets displaced by fresh data

As I work on creating HTML tags and assigning data, I encounter an issue with my code. Below is the snippet: MyCombo = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable ...

Creating a JavaScript function using jQuery to calculate the total sum of textboxes with two specified classes

I'm currently attempting to calculate the total of a group of textboxes by utilizing jquery. Each textbox is styled with a class (class1) using bootstrap. To execute the jquery function, I've added an extra class (class2). Below is an example of ...

Prevent the bootstrap dropdown menu from closing when encountering a login error during form validation using ajax and codeigniter

I encountered an issue with my dropdown menu login that utilizes bootstrap ajax and codeigniter. When I attempt to submit the form and there is an error, I have to click multiple times before the error message appears because the dropdown menu keeps closin ...

JavaScript will continue to run uninterrupted even after refreshing the webpage

Has anyone else encountered the issue of a javascript on a page continuing to run even after the page is refreshed? From what I understand, javascript is single-threaded and should stop running when the page is refreshed. Just to provide some background, ...

Is it possible to pass a JSON key as a string in the @Input() decorator in Angular?

I am currently working on implementing angular material autocomplete in a custom component that can be easily used throughout my code. The challenge I am facing is setting up dynamic arrays with different keys for each array. Here is what I have attempted ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...

Maximizing the benefits of the express.js API through functions such as fetching data with get, sending

As someone who is just starting out in web development, I have recently delved into node and express 4.9.0. After going through some tutorials and experimenting with the API, it's clear to me that the http protocol and request URLs are essential comp ...

Error message: When using the Three.JS STL Loader, an Uncaught TypeError occurs because the property 'scale' is being called on an undefined value

I am currently loading five elements using the STL Loader in order to create a table. My goal is to use dat.gui to adjust the scale of Tabletop.STL. Here is the code snippet: <!DOCTYPE html> <html lang="en> <head> <title& ...

Using the $.each method instead of a traditional for loop

validateScaledIntegerNumberGridFields: function(frm) { var fields = $('.scaledInteger', frm); var result = true; $.each(fields, function(index) { var scale = $(this).data("scale"); ...

Javascript is currently facing issues with callbacks not functioning properly in an asynchronous manner

Attempting to execute one function after another in my discord.js code. Here is what I have: function1(function2) async function function1(callback) { var guild = client.guilds.cache.get(config.Server); let channels = guild.channels; fo ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...