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

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

Exploring methods for handling svgs incorporated in angular.js templates with webpack

I'm currently working on cache-busting my SVGs and other files like translation JSON. The issue I'm facing is that webpack does not seem to recognize imported svgs in the following format: <md-icon md-svg-src="assets/icons/ic-edit.svg">&l ...

Tips for updating the value of an input text field in one HTML table according to a certain value entered in a different input text field located in another HTML table

I am working with an HTML table that consists of one row. Within this row, there are two TDs which each hold their own tables (each containing 10 rows with 10 input fields). My goal is to update the value of another corresponding text field based on change ...

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

Calculator: Show individual digits once more following a calculation

After clicking the 'equal' button, the result is displayed. However, if I click another number, it doesn't clear the result. I want the result to stay when operation symbols like '+' or '/' are pressed. While working on t ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

a guide on monitoring the status of a stripe transaction through a straightforward form and javascript

Currently, I am in the process of setting up Stripe checkout for my website. I have successfully implemented the payment form, but now I need to figure out how to redirect the user to another page after a successful payment. Below is the JavaScript code th ...

Sending JSON Data from Angular2 Component to Node.js Server

Currently, I am facing an issue where I am unable to successfully insert data into a database using Angular2 and Node.js. Upon running my script, I use console.log(this.address); to verify that I am passing json, and the output in the console is as follow ...

Create dual modules within a single project

I am working on a mean-stack project. In my index.js, at the end, I have: router.get('*', function(req, res) { res.sendfile('./views/index.html'); }) module.exports = router; Now, I need to handle all webpages that match https://l ...

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Enhance your Next.js application with beautifully styled formatting using prettier

Looking for some assistance in setting up prettier with my next.js project. I have the following configuration defined in my package.json file: "scripts": { "format": "prettier --write \"**/*.{js, jsx}\"", }, My project structure includes sever ...

Navigating through different sections of your Angular app can be easily accomplished using

My current project structure is set up like this: The application I am working on is hosted in a subdirectory called /my-scripts/vk.plants. This means that when I request this URL, it loads layout.html and returns it to the user. layout.html contains the ...

There appears to be an issue with displaying the graph

I am having trouble understanding how to transfer the values entered in the input to the graph that is displayed successfully. Although the update seems correct, nothing changes when I try to update it and the data remains stagnant. Page.vue <script&g ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Utilizing the mobile navigation layout for desktop screens without the need to adjust breakpoints

Having created a responsive site with common breakpoints established in SCSS as mixins, I am now seeking to implement the mobile breakpoint for a single page on desktop view only. Initially, my plan was to create a 'forced-mobile' class by exten ...

What is the best way to use a JavaScript function as a callback?

I'm struggling with understanding callbacks, especially how they function. Here is my function: function checkDuplicateIndex(values, callback) { $.ajax({ type: "POST", url: url, data: "command=checkIndexAlbumTracks& ...

Dynamic image swapping using JSON key in Angular

Trying to display different icons based on a property that contains specific words. If the property includes "Health Care" or "Health Care .....", I want to show one image, otherwise another. I've tried using ng-show but my syntax seems off. Any sugge ...