What could be causing the player to take damage when either the bullet disappears or when they are hit?

I've encountered a problem with my code where bullets causing damage to the player even after despawning or hitting an edge. It's difficult to troubleshoot since the damage is applied passively, making it challenging to isolate specific collisions.

function shootPlayer() {
    if (!document.body.contains(enemy)) return;  // Stop if the enemy is removed

    const playerRect = player.getBoundingClientRect();
    const playerCenterX = playerRect.left + playerRect.width / 2;
    const playerCenterY = playerRect.top + playerRect.height / 2;
    const enemyRect = enemy.getBoundingClientRect();
    const enemyCenterX = enemyRect.left + enemyRect.width / 2;
    const enemyCenterY = enemyRect.top + enemyRect.height / 2;

    const angle = Math.atan2(playerCenterY - enemyCenterY, playerCenterX - enemyCenterX);

    const bullet = document.createElement('div');
    bullet.className = 'bullet';
    bullet.style.position = 'absolute';
    bullet.style.top = `${enemyCenterY}px`;
    bullet.style.left = `${enemyCenterX}px`;
    document.body.appendChild(bullet);

    const bulletSpeed = 5;
    const bulletDamage = 5;

    function moveBullet() {
        let bulletTop = parseFloat(bullet.style.top);
        let bulletLeft = parseFloat(bullet.style.left);

        bulletTop += bulletSpeed * Math.sin(angle);
        bulletLeft += bulletSpeed * Math.cos(angle);

        bullet.style.top = `${bulletTop}px`;
        bullet.style.left = `${bulletLeft}px`;

        console.log(`Bullet Position: (${bulletLeft}, ${bulletTop})`);

        // Simple collision detection with the player
        if (
            bulletLeft >= playerRect.left &&
            bulletLeft <= playerRect.right &&
            bulletTop >= playerRect.top &&
            bulletTop <= playerRect.bottom
        ) {
            decreasePlayerHealth(bulletDamage);
            bullet.remove();
            console.log('Bullet hit the player.');
            return;
        }

        // Check if the bullet is out of bounds and remove it
        if (bulletTop < 0 || bulletTop > window.innerHeight || bulletLeft < 0 || bulletLeft > window.innerWidth) {
            bullet.remove();
            console.log('Bullet despawned.');
            return;
        }

        // Continue moving the bullet
        requestAnimationFrame(moveBullet);
    }

    requestAnimationFrame(moveBullet);
}

I have attempted various solutions within the if statement conditions without success. The decreasePlayerHealth function should only execute when the bullet successfully strikes the player.

Answer №1

When it comes to collision, I always find it to be quite challenging. However, there are a few tips and tricks that may help in making it work smoothly:

1: Double-check if the function decreasePlayerHealth() is being called elsewhere in your code.

2: In your collision detection process, start by verifying if the bullet is out of bounds before moving on to checking for player collisions. Sometimes simply rearranging the order of operations can make a big difference.

Having experience with game physics myself, I understand how complex it can be. Gathering all the necessary data and considering restructuring your code could potentially lead to a breakthrough. Don't be afraid to try different approaches to see what works best.

I hope these suggestions prove beneficial to you.

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

"Attempting to send a jQuery post to a node.js server, but encountering an issue with missing request

Could really use some assistance here. I've hit a roadblock and can't seem to find the solution anywhere, not even in sample codes or google search results. Something just isn't right. The issue arises when I make a jQuery post request to m ...

What is the best way to switch between two components using vue.js?

I have a scenario where I need to toggle between two components, Register.vue [`my_reg-page`] and Login.vue [`my-signin_page`]. If the user opens the register page in the browser (using the /register URL), clicking on the Login heading will toggle the user ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

What is the best way to merge render and composer functions?

In my project, I have created two scenes: one for regular objects and another for clone objects with special effects using EffectComposer (BloomPass, FilmPass). I attempted to use renderer.render(scene, camera) along with composer.render(), but unfortunate ...

Attempting to grasp the concept of Thennables within the VSCode API. Can these TypeScript code examples be considered equivalent?

I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable. This is my first encounter with it, and the one returned from this function doe ...

Determining the emptiness of an array in Postman using node.js

When I receive a response, it is in the following format: { "test1": [], "test2": [], "test3": [], "test4": null, "test5": [] } This is the response that I get after making a request. I need to verify whether test1 is empty or not. ...

What is the process for refreshing information in VueJS?

<script> export default { data() { return { data: {}, dataTemp: {} } }, methods: { updateData() { let queries = { ...this.$route.query } this.data = { ...this.data, pID: queries.pid, s ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

Mastering the art of raycasting onto a point cloud in ThreeJs R71

I am currently working with Autodesk Forge, leveraging Three.js r71, and I am looking to implement a raycaster to identify clicks on various elements within a point cloud. If anyone could provide a sample code snippet on how to achieve this using Three.js ...

Performing an AJAX call every half-hour using JavaScript

I am looking to implement an ajax request every 30 minutes using JavaScript. Specifically, for the user currently logged in, I aim to retrieve any notifications that have a start date matching the current time. These notifications are set by the user with ...

Arrange pictures into an array and showcase them

I'm encountering some difficulties with organizing my images in an array and displaying them in a canvas element. Javascript code snippet canvas = document.getElementById('slideshow'); canvasContent = canvas.getContext('2d'); va ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

Issue with Iconify icon not updating when "data-icon" is set using setAttribute()

I'm having trouble trying to animate or replace an icon using the "setAttribute" method. Can someone take a look at my code and help me figure out what's wrong? <!DOCTYPE html> <html> <script src="https://code.iconify.design/1/1 ...

Tips for determining the duration between the Monday of last week and the Sunday of last week

Can anyone help me figure out how to retrieve the dates from last week's Monday to last week's Sunday using JavaScript? I've searched through various sources with no luck. Hoping someone here can provide some guidance. ...

Create a substitute for Object.seal, Object.freeze, and Object.preventExtensions applications

Is there a way to freeze an object's existing properties while still allowing new ones to be added? I can't seem to find any built-in functionality for Object.freezeExisting(), so maybe it's worth considering implementing it, possibly even w ...

Modify data in JSON using ngModel and then send it via HTTP POST request

Greetings, I am relatively new to Angular and find myself in a bit of a quandary. It seems like the solution to my issue might be simpler than I think. My Angular App consists of a basic "Page View/Controller" and an "Admin View/Controller" that both util ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Guide to dynamically loading customer data into an HTML table using JavaScript

I'm looking to populate a table with data on customers including their name, customer ID, and rental cost. Can anyone help me with the JavaScript code needed to insert this data into rows of the table? Your assistance is greatly appreciated. Below is ...