The elusive button refuses to disappear within the realm of p5 javascript

I'm encountering a problem trying to hide a custom button I made using p5.js:

var quit_button;
var pause = false;

function keyPressed() {
  if (keyCode == '80') { // If p is pressed on the keyboard
    if (pause === true) {
      quit_button.hide()
      pause = false;
    } else {
      pause = true;
    }
  }
}

function restart() {
  quit_button.hide() // This doesn't seem to work
  pause = false;
  setup()
}

function setup() { // Initial screen setup
  createCanvas(600, 400);
}

function draw() {
  background('#fae'); // A fresh canvas is created
  if (pause === true) {
      quit_button = createButton('quit')
      quit_button.position(300,200)
      quit_button.mousePressed(restart)
      text("Game has been paused. Press P to resume.", 100, 100)
    } else {
    }
}

When running the code and hitting p to pause my snake game, it indeed pauses as expected. However, when attempting to unpause by pressing p again or by clicking 'quit', the quit button remains visible.

Answer №1

When the game is in its paused state, a new button is being generated every single frame. This results in having 60 buttons created per second, essentially piling up on top of each other. To visualize this, simply right-click on the button and select inspect element to see all the overlapped buttons on your screen.

To resolve this issue, it's crucial to ensure that only one button is ever created. You can achieve this by checking if the variable quit_button has already been initialized, and if so, bypass the creation process:


if(!quit_button){
    quit_button = createButton('Quit Game')
}

An alternative approach would be to place this button creation code at the beginning while keeping it hidden by default.

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

Displaying information before completing map zoom and pan on Bing AJAX map

When using my Bing Ajax Map app, users are presented with a list of locations to choose from. Upon clicking on a row, the map centers and zooms in on the selected location. However, I've encountered an issue where the info window loads before the map ...

Skipping an iteration in ng-repeat in Angular 1.0.8: A simple guide

Is it possible to skip a particular iteration in ng-repeat without modifying the underlying array/object being iterated over? Consider the following example: var steps = [ { enabled: true }, { enabled: true }, { ...

Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they ...

What is the process of integrating Bootstrap into a Node project?

I recently set up a MEAN stack project using npm and am currently including Bootstrap via CDN: link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css') However, I want to add Bootstrap using ...

Is there a way for me to retrieve both a ModelAndView file and a string?

Can JavaScript return an object and a string simultaneously? const myModel = new Map(); if (preview === "pdf") { myModel.set("IS_IGNORE_PAGINATION", false); myModel.set("format", "pdf"); } else if (preview === "xls") { myModel.set("IS_IGNO ...

Creating a PNG image on a canvas, converting it to a data URL, and then transmitting it using an XMLHttpRequest in NodeJS/Express

I've been experimenting with different methods found on Google, but so far none have worked for me. I'm currently working on implementing the signature-pad, a JavaScript/HTML5 canvas solution for eSignatures. My goal is to save the canvas data as ...

What is the best way to populate an array with unique values while applying a condition based on the objects' properties?

Looking to create a unique exam experience for each student? I have an array of question objects and the goal is to select random and distinct questions from this array until the total sum of scores equals the specified exam score. This means that every s ...

Is there a way to switch the cursor to a pointer when hovering over a bar on a ChartJS bar graph?

Here's the chart I created: createChart = function (name, contributions, idArray) { globalIdArray = idArray; var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: "bar", data: { lab ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

Ways to decrease the size of this item while maintaining its child components?

Here is an object that I am working with: { "name": "A", "children": [ { "name": "B", "open": false, "registry": true, "children": [ { ...

Prevent duplicate submissions by disabling the ASP.NET Forms button after it has been clicked

How can I disable an ASP.NET button after it's clicked to prevent double-clicking, and then enable it again after the submission is complete? I need some assistance with this. ...

What are some alternative solutions when functional component props, state, or store are not being updated within a function?

Initially, I need to outline the goal. In React frontend, I display data that aligns with database rows and allow users to perform CRUD operations on them. However, in addition to actual database rows, I include dummy rows in the JSON sent to the frontend ...

Update submenu panel in jQuery Mobile version 1.4.3 following AJAX request

Hello there, I am currently in the process of developing my first JQuery Mobile website. One of the key features I have implemented is a panel for navigation. Each individual page includes the panel, along with an icon in the header that serves as the butt ...

UI and `setState` out of sync

Creating a website with forum-like features, where different forums are displayed using Next.js and include a pagination button for navigating to the next page. Current implementation involves querying data using getServerSideProps on initial page load, f ...

What steps should I take to resolve the 'buffer' issue in my jsonwebtoken?

As I am still new to ReactJS and the MERN stack in general, the code in Activate.js below essentially means that when the useEffect() hook is triggered, we will receive the jwt token extracted from the route parameter/url using the {match} props. This toke ...

Determine your age by manually inputting your date of birth

Utilizing Ajax Calendar, I have successfully implemented a feature to calculate age based on the date selected in one textbox and display it in another. However, I am facing two challenges. First Issue:- I want the Age Textbox to be disabled so users cann ...

Change the background color of the MUI ToggleButton that is currently selected

I need help figuring out how to change the background color of a selected toggle button. Currently, the buttons are functional but do not visually indicate when one is selected. I would like the first button (Btn 1) to have a default color, and if the us ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

The functionality of Mongoose async promise appears to be malfunctioning

Struggling with using async in conjunction with mongoose. Here's my code snippet : function() { SchemaOne.findById(fooIdOne).exec().then( x => { // Some initial instructions myCollection.foreach( y => { SchemaTwo.findById ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...