The bouncing ball in p5.js is not triggering the conditional statement

I am brand new to JavaScript and p5.js. While I realize this may not be the most efficient code for a bouncing ball, I wanted to challenge myself by writing my own bouncing ball mechanic as part of my self-learning journey.

function draw() {
    background (col); // setting background color
    col = map(cir.x, 0, 600, 0, 255) // mapping color values

    fill (350, 200, 200);
    ellipse (cir.x, cir.y, cir.diameter, cir.diameter);

    // Bouncing ball mechanism
    var speed = 3;
    var hitRightWall = false;
    var hitLeftWall = false;

    if (cir.x >= 300) {
        hitRightWall = true;
        hitLeftWall = false;
    }
    else if (cir.x <= -50) {
        hitLeftWall = true;
        hitRightWall = false;
    }
    if (hitRightWall) {
        speed = -3;
    }
    else {
        speed = 3;
    }
    cir.x = cir.x + speed;
}

Despite activating the if (cir.x >= 300) condition, the if (hitRightWall==True) condition is never triggered. As a result, the ball continuously moves right and eventually off the screen.

Answer №1

Here are a few things to consider in your code. Firstly, you are resetting the values of hitRightWall and hitLeftWall to false every frame. Is this intentional?

Secondly, take note of statements like this:

hitRightWall == true;

The use of == for comparison instead of assignment may not be what you intended. You may want to use:

hitRightWall = true;

Using = is the correct way to assign values to variables.

Lastly, it might be worth reassessing if you really need these variables. Could you directly modify the speed variable within your initial if / else if statement?

For additional reading, feel free to check out this tutorial on collision detection: here. Though it's for Processing, the concepts can still apply to P5.js.

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

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...

Incorporating Angular, Angular UI, and Typescript while using the "controller as" approach

I'm having trouble with the combination in the topic, there must be a minor mistake somewhere that's causing this issue. Controller: class JobCtrl { job: Object; public $inject = ['$log', '$resource', &apos ...

Troubleshooting: Why are my images not displaying in webpack and node.js setup?

My problem: I'm facing an issue with background images in my project. I have included two images and used file-loader to bundle them through webpack. While the images display correctly in the app during development using webpack-dev-server, they disap ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

The connection between Mongoose and the nodejs app cannot be established

I've been attempting to integrate Mongoose with my Node.js environment, but I'm encountering an unexpected error. Previously, I was able to connect with Mongoose using the same commands, but for the past few days, it's been throwing errors. ...

Error in Next Js: Invalid element type provided. Expected a string for built-in components or a class/function for composite components, but received an undefined value

Received an error message stating: "Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

JavaScript Tutorial: Extracting the text content of a drop event

Curious about extracting the text value from a drop event, I set out to find an answer. To my surprise, I discovered that it's not as straightforward as I thought. Check out the demo below: <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

What is the best way to display all the properties of an npm package in an aesthetically pleasing format?

My curiosity leads me to explore the various methods and properties of components like GoogleMapReact. I attempted the following code: import GoogleMapReact from 'google-map-react' console.log(GoogleMapReact); However, the output is a long, mess ...

What steps should I take to ensure the proper functioning of this loop/function?

Currently, I'm in the process of developing a rock-paper-scissors game that utilizes prompts for player input. Below is the full code snippet: var options = ['R','P','S','r','p','s'] var user ...

Selenium WebDriver producing unexpected results with getTitle() method

Currently, I am executing an automated test script in a selenium-webdriver environment using Phantomjs. My approach involves running the script through node.js, rather than utilizing Python or C#. The steps I took to set up the environment are outlined b ...

Linking AngularJS directives with HTML elements following an AJAX call

Having trouble getting the 'customers-invoice.html' file to work with my Angular app after loading it through ajax. Any suggestions on how to bind them together?” <body ng-cloak ng-app="myApp"> <main id="main"> <div ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Limit access to the server in Node.js by allowing loading only if the request is coming from another page and form POST variables are present

After searching for documentation without success, I have a question: Is there a way to prevent users from directly accessing my node.js server at website.com:3000? Currently, when a user visits my node.js website, it crashes the whole server and takes i ...

Using jQuery to iterate through an open dialog box

I want to add a small animation for the user to indicate that their submission is in progress. $("#textscreen").dialog({ modal: true, draggable: false, open: function(event, ui) { $(this).everyTime("1s", function(i) { var d ...

Enhance the functionality of the button by implementing AJAX with the use of data

I am currently working on implementing an update function without using forms. Instead, I am utilizing data-* attributes and ajax. My goal is to prevent the button from triggering after updating the values. However, I am facing an issue with my script as ...

Converting a class-based component into a functional component

TL;DR : I am in the process of converting my class-based App component to a Functional component but encountering unexpected outcomes with the useEffect Hook. Being relatively new to React, I originally built my movie search app using a class-based approa ...