The hit detection algorithm seems to be malfunctioning, and the reason behind it is unclear. (Using Javascript/Processing

I am a beginner in game programming and programming in general. In the past, I have created a clone of "Flappy Bird" and some other games using the hit detection algorithm from the Mozilla Developer Network here.

Currently, I am facing an issue while trying to recreate the classic game "Pong". The ball is supposed to hit the paddle and bounce back, but for some reason, it's passing through the paddle. I am using the Processing.js library and the draw() function is called frequently by processing.js.

You can view the code in action (not working as expected) here


var PADDLE_WIDTH = 10;
var PADDLE_HEIGHT = 75;
var PADDLE_X = 10;

var Player = function(y) {
    this.x = PADDLE_X;
    this.y = mouseY;
    this.score = 0;
    this.width = PADDLE_WIDTH;
    this.height = PADDLE_HEIGHT;
};


Player.prototype.drawPlayer = function() {
    rect(10,mouseY, this.width, this.height);

};



var Ball = function(x,y) {
    this.x = x;
    this.y = y;
    this.speed = 4;
    this.width = 10;
    this.height = 10;
};

Ball.prototype.drawBall = function() {
    rect(this.x, this.y, this.width, this.height);

};

Ball.prototype.onHit = function() {
    if(this.y <= 0 || this.y >= height) {
        this.speed *= -1;
    } else if(this.x <= 0 || this.x >= width){
        this.speed *= -1;
        // HIT DETECTION UNDERNEATH
    } else if (player.x < this.x + this.width &&
   player.x + player.width > this.x &&
   player.y < this.y + this.height &&
   player.height + player.y > this.y){
       this.speed *= -1;
   }

};

var player = new Player();
var ball = new Ball(width/2, height/2);



draw = function() {

    background(0);
    fill(250, 250, 250);
    ball.x -= ball.speed;

    player.drawPlayer();
    ball.drawBall();
    ball.onHit();

};

Answer №1

Within the drawPlayer function, the player is currently being drawn at the coordinates of (10, mouseY). However, the y property of the player is not being updated, thus it always remains at 0. To address this issue, I recommend implementing an update method that will modify the player's state. Additionally, adjust the draw method to render the player based on its current state. Here’s an example:

Player.prototype.updatePlayer = function() {
    this.y = mouseY;
};

Player.prototype.drawPlayer = function() {
    rect(this.x, this.y, this.width, this.height);
};

draw = function() {
    // ... 
    player.updatePlayer();
    player.drawPlayer();
    ball.drawBall();
    // ...
};

Answer №2

Within the drawPlayer function, you can incorporate the line this.y = mouseY

Player.prototype.drawPlayer = function() {
    rect(10,mouseY, this.width, this.height);
    this.y = mouseY;        
};

Check out the fiddle here: http://jsfiddle.net/z0acb8gy/

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 more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Resetting initial values with Velocity.js post-animation

After animating elements into view on a page, I want to defer further animation through CSS classes. However, Velocity keeps all animated properties in the style= tag, hindering CSS transitions. My solution involves resetting the CSS upon completion, but ...

Error: The symbol $ is not recognized

This is a snippet of code that I've written to automate address filling and extract latitude/longitude/address information. <html> <head> <LINK rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" sr ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

The content inside the bootstrap modal is not visible

My goal is to trigger a modal window when a specific div is clicked using bootstrap modal. However, upon clicking the div, the screen darkens but the modal body fails to appear. Code: <html> <head> <title></title> ...

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Dimensions of HTML Container on Google Website

I'm attempting to incorporate a collapsible table using HTML Box in a Google site. The code for the collapsible table can be found at http://tutorials.seowebpower.com/google-sites-advanced/collapsible-table. Here is the code: <html> <head> ...

Simple way to extract the values from every input element within a specific <tr> tag using JQuery

Is there a way to align all input elements in a single row within my form? For example, consider the snippet of code provided below, which includes a checkbox and a text input box. I would like to retrieve the values from both of these input types and pres ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

Sticky positioning causes elements to stick to the window as the

https://i.stack.imgur.com/nv3vU.png I am facing an issue with a position sticky block that can vary in height relative to the window size. Sometimes, the block is taller than the viewport, making it impossible to scroll to see all the content. Is there a ...

Retrieving variables from JavaScript files in TypeScript

Greetings, I am in the process of upgrading an existing Angular application from version 2 to 9. My approach involves first moving it to angular 4 and then continuing with the upgrades. I have successfully updated the necessary packages, but now I'm e ...

Implementing pagination and filtering in a single MERN controller

Is it possible to implement pagination and filtering in the same controller? Filter service:- const filterPosts = async (filterData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, data: { ...

Divs are the preferred placeholders over inputs and textareas

For the past few weeks, I have been trying to tackle a problem with creating placeholders that guide users on where to type. My goal is to make these placeholders disappear when users start typing and reappear if the div is empty again. All my attempts so ...

Material UI Table dynamically updates with Firestore real-time data

My current code aims to update a Material UI table in real-time with data from a Firestore database. I can fetch the data and store it in an array, but when I assign this array to the table data, nothing changes. I've heard that I should use states fo ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

Redirect to a new URL using $routeProvider's resolve feature

Currently, I am in the process of developing an application that includes the following endpoint: .when('/service/:id?', { templateUrl: 'views/service.html', controller: 'ServiceCtrl', resolve: { service: fu ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

angular-in-memory-web-api encounters a 404 error

I recently completed the heroes tour and now I am trying to work on something similar, but I seem to be having trouble understanding angular-in-memory-web-api. Here is a snippet of my code: clients-data.service.ts import { Injectable } from '@angular/ ...

Transform the appearance of the navigation bar background upon scrolling in Bootstrap

I am trying to change the background color of my navigation bar from transparent to black when scrolling. I want it to function like this template: . Previous attempts using solutions from How to Change Navigation Bar Background with Scroll? and Changing n ...

An issue with the Babel version is preventing the Express API from starting up successfully

Error! Message: [nodemon] starting `babel-node index.js` C:\Users\Zara Gunner\AppData\Roaming\npm\node_modules\babel-cli\node_modules\babel-core\lib\transformation\file\options\option-ma ...