Creating movement for a shape using the keyIsDown function in p5.js

Having some trouble with p5.js and trying to make a shape move on the canvas. However, instead of smoothly moving the shape, it's leaving a trail behind as it redraws in the new position. Not quite the effect I was going for. Take a look at the issue here.

Here is the code for my "Player" class (the shape that should be moving):

function Player() {
    this.hp = 10;
    this.x = 230;
    this.y = 240;
    this.color = "red";
    this.r = 10;

    this.spawn = function(){
        fill(this.color);
        noStroke();
        rect(this.x, this.y, this.r*2, this.r*2);
    }
}

This section contains my code within the setup and draw functions using p5.js:

var p1;

function setup() {
    createCanvas(500, 500);
    background("green");
    p1 = new Player();;
}

function draw() {
    p1.spawn();
    if (keyIsDown(LEFT_ARROW)) { 
        p1.x--;
    }
    if (keyIsDown(RIGHT_ARROW)) {
        p1.x++;
    }
    if (keyIsDown(UP_ARROW)) {
        p1.y--;
    }
    if (keyIsDown(DOWN_ARROW)) {
        p1.y++;
    }
}

Any tips or advice on how to fix this would be greatly appreciated. Thank you!

Answer №1

One way to ensure your canvas is clean and ready for new content is by utilizing the background() function in P5.js. It's best practice to place this function at the beginning of the draw() function. Take a look at this example:

function setup() {
  createCanvas(200, 200);
}

function draw() {
  background(64);
  ellipse(mouseX, mouseY, 25, 25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

Experiment with moving the background() function call to the setup() function to observe its impact on your sketch.

Answer №2

To utilize a key, follow these steps:

if (keyDown(the desired key)) {
 
}

Alternatively,

if(keyDown("the desired key")){


}

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

Tips for saving values created with JavaScript as an HTML file

I am looking to download an appended value as a HTML file. In my code, values are being appended from an external HTML file through an iframe. The code is functioning correctly and retrieving the right value. Now, I just need to download that appended valu ...

Updating MongoDB's binary data subtype

Is there a way to modify just the subtype of the Binary element in MongoDB? I currently have a Binary element in my database with type 0x00 BinData(0, xxx) Can this be done using the shell to only update the subType and change it to a different value ...

Navigate between tabs with a single click

Hey there! I'm having trouble putting together a webpage that features a sidebar. I want to make it so that clicking on one of the links at the top will switch the tab and its content accordingly. However, the current code I have isn't working an ...

Using ngStyle in AngularJS to dynamically adjust styling based on variable values

I am looking to create a progress bar using the uikit framework. The documentation states that it can be done like this: <div class="uk-progress"> <div class="uk-progress-bar" style="width: 40%;">40%</div> </div> However, this ...

Encountering a bug: "Undefined property" issue when working with Web Sockets in React Native

I'm a beginner in React Native and Java Script development, and I'm facing an issue while trying to retrieve a JSON object and display it on the client side. I keep getting a "cannot read property of undefined" error when using websockets instead ...

Should CSS variables be defined within the render method of a React component?

Yesterday, I mistakenly created and deleted a post. Now, I am facing an issue with creating a component that requires specific styling. The problem arises when the componentDidMount() method causes flickering during the rendering process, as it takes some ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

JavaScript encounters an Access Denied error when attempting to read data from a JSON file in

My code is experiencing issues on IE browser and Chrome, but works perfectly on FireFox. var currentPage = 1; var max = 0; var myList = []; var links = []; $.ajax({ cache: false, type : 'GET', crossDomain: true, ...

Repeated instances of the same name appearing in the dropdown list every time the tab button is clicked

When using my function in the onclick nav tabs event (triggered by clicking on any tab), I have a requirement where I need to ensure that no duplicate names are inserted into the dropdown list. The current function is working perfectly, but I am looking fo ...

Change the class to update the image when clicked using jQuery

Although I've researched several articles and answers on Stack Overflow, none of them have addressed my question thoroughly. Admittedly, I am quite new to jQuery and unsure about how to proceed. I am working on an HTML landing page where I aim to dis ...

The Jquery hide function seems to be unresponsive when trying to close the span in my Dialog

$('.ui-dialog-titlebar-close ui-corner-all').hide(); I'm having trouble hiding the close 'X' span in my jQuery dialog. When I resize the dialog, it appears, but it's not showing correctly initially due to CSS issues. Could s ...

Steps for ordering by a JSON attribute:

Within my JSON file, I have the following simple structure: {"Item1": {"p1": {"p1sub1": 8, "p1sub2": 7}, "p2": {"p2sub1": 6, "p2sub2": 5} }, "Item2": {"p1": {"p1sub1": 4, "p1sub2": 3}, "p2": {"p2sub1": 2, "p2sub2": 1} } } To retrieve this data, I use th ...

Is it possible to connect a date range picker custom directive in AngularJS with the behavior of AngularUI-Select2?

I'm currently utilizing Angular UI - Select2 directive for displaying an option box. Bootstrap Date-Range Picker for showing a date picker Both functionalities work effectively on their own. Functionality of the Date picker Whenever there is a ch ...

a expanding list with automatically loaded information

After trying various lists found online without success, it seems that the issue may be due to the dynamic loading of the list content using JQuery ajax. During $(document).ready, the list is loaded and the HTML data is appended to the div. Subsequently, ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

Implementing HTML rendering within a <script> tag using Vue.js

I'm attempting to display dynamic HTML within a script tag. As part of my project, I've created a custom data-table component and now I am trying to add a column for operations. However, I'm facing issues when trying to assign functions to ...

JavaScript event manually triggered not propagating within an element contained in an iFrame context

I am currently developing a WYSIWYG designer that enables users to choose colors through [input type="color"] fields. The interface includes inputs on the left side and an iFrame on the right side displaying the generated preview. Normally, when ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

Personalized customizable elements in Draft.js (extension)

For instance, I am interested in enabling users to incorporate a dynamic slideshow of images into their page using Draft.js. This would allow them to select a predefined slideshow from my app and have it automatically update on their page if the images a ...

Adapting to more user inputs in accordance with the feedback received from the AJAX response

Two user inputs are being received: area time Utilizing this information, the available restaurants in the specified area during that particular time are displayed. In addition, all the cuisines offered by these restaurants are displayed as checkboxes. ...