简体   繁体   English

在p5.js中来回移动rect时停止延迟

[英]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). 我正在使用keyPressed函数,当我向左移动时,突然又迅速开始向右移动,我的矩形刚刚停止(反之亦然)。 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;
    }
}

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. 您的代码检测到您释放了左键,并将移动速度设置为0,这就是您停止移动的原因。

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. 为此,您需要跟踪关注的每个键的布尔变量,在keyPressed()keyReleased()函数中设置这些布尔值,然后在draw()函数中检查这些布尔值。

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. 本教程适用于处理,但是相同的想法也适用于P5.js。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM