Create engaging animations using JavaScript to draw moving circles on an

I'm attempting to achieve a seamless animation of a moving circle from one set of coordinates to another. In this particular scenario, the circle moves from (10, 10) to (50, 50). Below you can find the code for my Bullet class. Whenever the user presses the spacebar, a new instance of the Bullet object is created with the goal of animating it smoothly. How can I accomplish this?

class Bullet{
    
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.size = 10;
    }

    draw(){
        ctx.fillStyle = "green";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
        ctx.fill();
    }
    fire(locationX, locationY){
        
    }
}

document.addEventListener('keydown', function(e){
        if(e.key == ' '){
            var currBullet = new Bullet(10, 10);
            currBullet.fire(50, 50);
        }
});

function reset(){
    ctx.clearRect(0, 0, w, h);
}

Answer №1

Utilize the requestAnimationFrame function to create dynamic bullet animations. What is your main objective with this implementation? Are you aiming to shoot bullets from point (10, 10) to (50, 50)? Is there a need to constrain the distance traveled by the bullets? Or do you plan to shoot them in the direction based on the player's orientation? Are you considering restricting the number of bullets?

This piece of code fulfills your request, but it has certain limitations.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;

let bullets = [];

class Bullet{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.size = 10;
    }

    draw(){
        ctx.fillStyle = "green";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
        ctx.fill();
    }
    update(){
        this.x += 1
        this.y += 1
    }
}

document.addEventListener('keydown', function(e){
        if(e.code === 'Space'){
            fire()      
        }
});

function fire() {
    bullets.push(new Bullet(10, 10))
}

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (let i=0; i < bullets.length; i++) {
    bullets[i].draw()
    bullets[i].update()
    if (bullets[i].x >= 50 && bullets[i].y >= 50) {
      bullets.splice(i, 1)
    }
  }
  
  requestAnimationFrame(animate)
}
animate()
<canvas id='canvas'></canvas>

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

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

How can JavaScript be used to delete cache and cookies?

Looking for a solution to clear cache and cookies via JavaScript? I'm currently using Selenium for testing in Microsoft Edge, but the tests are running in the same session as the previous run. I need each test to run in a clean session every time. Unf ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

Converting a 3D model from Unity to three.js for seamless integration

I am tasked with building a human body model in WebGL using three.js, but I only have a Unity model. Is there a way to export the Unity model as an object or something similar for this purpose? ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

Stacking SetIntervals on top of each other

I've been working on a project that involves using setInterval, but I'm struggling to grasp how it functions. The issue I'm encountering is that every time I invoke setInterval, the function appears to be stacking on top of one another, caus ...

Synchronize CSS Properties with JavaScript Event

Is there a more efficient way to synchronize two properties using JavaScript or JQuery? For instance, when I have an editable text field and I switch it to an input box upon double click, how can I ensure that the input box adjusts its size along with the ...

ReactJS: Error message indicating that the update depth limit has been exceeded

I'm facing an issue with toggling the state of a component in ReactJS. The error message I am receiving says: Maximum update depth exceeded. This can occur when a component repeatedly calls setState within componentWillUpdate or componentDidUpdate. ...

Utilizing Apps Script for tallying background colors in Google Sheets

Sorry for the lengthy explanation! Let me know if you need more details or examples from the JavaScript file/spreadsheet I'm working with. Situation: I'm facing challenges with Google Apps Script (GAS) while trying to count the number of backgro ...

What is the process of converting a value from an HTML form into a PHP variable?

I am looking to update the order preparation time. I have created an HTML form, but I am facing issues passing it into a PHP variable after this code block. I have tried using Cookies and POST method, but neither has helped me so far. <form> ...

Transmitting a 2D array to the server and retrieving it using JavaScript

I used to send data to the server using a one-dimensional array in C Arduino language. Now, I need to figure out how to send a two-dimensional array instead. typedef struct { String Name; String addr; String ttl; }officeKownNetworks; officeKownNetwo ...

Creating a new file for a promise function

Initially, I managed to make this function work within a single file. However, I prefer organizing my code by splitting it into multiple files. // library.js file module.exports = { get: () =>{ return new Promise((reject, resolve) =>{ ...

Save the language code (ISO 639) as a numerical value

Currently, I'm working with a MongoDB database and have made the decision to store certain information as Numbers instead of Strings for what I thought would be efficiency reasons. For instance, I am storing countries based on the ISO 3166-1 numeric s ...

Issue with Trix text editor not triggering the change event

Lately, I've been facing some difficulties in getting the tirx-change event to trigger when there are changes in the content of a trix-editor. Despite using React JS for the view, I haven't been able to identify the problem. Below is the code sni ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} https://i.sstatic.net/1AnDi.png I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="displa ...

Retrieve information from a JSON file by utilizing the JSON file itself as a variable

Currently, I am attempting to extract the URL of an attached photo using JSON. I am utilizing the value of the data from the JSON key "HousePhoto1" to then access the value from the post_media data. The issue I am encountering is that my JavaScript code fa ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...