jholsch29
jholsch29

Reputation: 77

Stopping delay when moving a rect back and forth in p5.js

I am writing a game in progress and I ran into a little problem. I am using the keyPressed function and when I am moving the the left, then I suddenly and quickly start moving to the right, my rectangle just stops (vice versa). There will be dodging in my game, so it is important to be able to switch direction as fast as possible. What should I do?

//main file, sketch.js: 

var person;

function setup() {
    createCanvas(380, 720);

    person = new Person();
}

function draw() {
    background(64, 64, 64);
    person.show();
    person.move();
}

function keyReleased() {
    if (keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW) {
        person.setDirX(0);
    }
}

function keyPressed() {
    if (keyCode === RIGHT_ARROW) {
        person.setDirX(1)
    }

    else if (keyCode === LEFT_ARROW) {
        person.setDirX(-1);
    }
}

//person(rectangle) file, person.js:

function Person() {
    this.x = width/2;
    this.y = height - 20;
    this.xdir = 0;
    this.ydir = -0.25;

    this.show = function() {
        noStroke();
        fill(250);
        rectMode(CENTER);
        rect(this.x, this.y, 25, 25);
    }

    this.setDirX = function(dir) {
        this.xdir = dir;
    }

    this.move = function(dir) {
        this.x += this.xdir * 5;
        this.y += this.ydir;
    }
}

Upvotes: 0

Views: 230

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42174

Try to think about what keys you're pressing and releasing when you quickly go from holding in left to holding in right. This is what you're doing:

  • First you hold down left.
  • Then you hold down right. So for a split second you're holding down both keys.
  • Then you let go of left, but continue holding down right.

Your code detects that you released the left key and sets the movement speed to 0, which is why you stop moving.

To fix this, you're going to want to keep track of which keys are currently pressed. You do this by keeping track of a boolean variable for each key you care about, setting those booleans in your keyPressed() and keyReleased() function, and checking those booleans in the draw() function.

Shameless self-promotion: I wrote a tutorial on using this approach here. See the section titled "Handling Multiple Keys". This tutorial is for Processing, but the same idea applies to P5.js.

Upvotes: 2

Related Questions