Problem with detecting collisions algorithm

Here is the jsfiddle I've been working on: http://jsfiddle.net/TLYZS/

Upon debugging the code and inspecting the collision function, it's evident that the collision is functioning properly when the user overlaps with the other character. However, in a fighting game scenario, the collision should not work in this manner:

  1. It's noticeable that when I attempt to punch or kick the character from a slight distance, the collision detection function fails to register the impact even though it appears visually on the screen that the user is engaging with the character.
  2. How can I adjust the collision detection function to enhance its accuracy?

    function Collision(r1, r2) {
            return !(r1.x > r2.x + r2.w || r1.x + r1.w < r2.x || r1.y > r2.y + r2.h || r1.y + r1.h < r2.y);
        }
    

Answer №1

Below is a vintage JS implementation of flash.geom.Rectangle. Feel free to incorporate it into your current project:

function Rectangle(x, y, w, h) {  //  constructor
    if(x==null) x=y=w=h=0;
    this.x = x;      this.y = y;
    this.width = w;  this.height = h;       
}
Rectangle.prototype.isEmpty = function() {  // : Boolean
    return (this.width<=0 || this.height <= 0);
}
Rectangle.prototype.intersection = function(rec) {  // : Rectangle
    var l = Math.max(this.x, rec.x);
    var r = Math.min(this.x+this.width , rec.x+rec.width );
    var u = Math.max(this.y, rec.y);
    var d = Math.min(this.y+this.height, rec.y+rec.height);
    if(r<l || d<u) return new Rectangle();
    else           return new Rectangle(l, u, r-l, d-u);
}

Simply use the following code snippet:

var r1 = new Rectangle( 0, 0,100,100);
var r2 = new Rectangle(90,90,100,100);
// r1.intersection(r2) would be Rectangle(90,90,10,10)
if( !r1.intersection(r2).isEmpty() ) ... // there is a collision

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

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

Utilize CSS with dynamically created elements

I am currently figuring out how to use my .each() function with a $(document).ready and a click event. Here's what I have so far: $(document).ready(function(){ $(".help-inline").each(function() { $(this).css('display', 'none&apos ...

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

My component is not executing the onClick function as expected

I am facing an issue with a component that I imported into another component. Despite clicking on the component, the onclick function does not execute. Here is the code snippet for the component: const HomeFeedCard = ({ name, image, published, quantity, w ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

Employing useEffect within Material-UI tabs to conceal the third tab

At the page's initial load, I want to hide the first two tabs. The third tab should be visible with its content displayed right away. Currently, I can only see the content after clicking on the third tab. To troubleshoot this issue, I attempted to use ...

When additional elements follow, the button ceases to function properly in JavaScript

I am working on creating a text-based idle game that involves multiple buttons and text around them. However, I have encountered an issue where the functionality stops working when I try to add text after the "Work" button. The callback function is no lon ...

Utilize the data storage API within Next.js or directly in the user's

Struggling to store this ini file on either the server or client, any help would be greatly appreciated. Additionally, I would like to display the ini info in the browser so that clients can easily copy and paste the information. However, I seem to be fac ...

What happens when Google Polymer platform is used without defining _polyfilled?

My attempt at creating a simple example using Google Polymer's platform.js is running into an error message that says: Uncaught TypeError: Cannot read property '_polyfilled' of undefined This is what I'm attempting to achieve: <cur ...

What is the best way to incorporate npm packages and ES6 features into Django?

As I work on the frontend development of my Django application, I am keen on incorporating the official material design components. Yet, I am faced with a challenge in seamlessly integrating these components. I am looking for a way to import the npm packa ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Node js - Looping Through Loading

I am facing an issue with my Node.js application. It runs perfectly fine on my local environment, but when I try to run it on my server using forever, the page just keeps loading without displaying anything. There seems to be no response and it gets stuc ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...

Can $refs cause issues with interpolation?

I'm currently learning Vue.js and the course instructor mentioned that modifying the DOM element using $refs should not affect interpolation. In fact, any changes made directly to the DOM will be overridden by interpolation if it exists. However, in m ...