keyPressed()函数不能平滑地渲染

时间:2016-12-29 23:09:55

标签: javascript p5.js

我刚开始使用p5.js,我喜欢简单,但有一件事我无法理解。

我设置了以下Fiddle

function Player(location, width, height, speed, weight) {
    this.pos = location;
    this.width = width;
    this.height = height;
    this.velocity = speed;
    this.mass = weight;
    this.grav = new p5.Vector(0, this.mass * 10);
}

function Wall(location, width, height) {
    this.pos = location;
    this.width = width;
    this.height = height;
}

var p1 = new Player(new p5.Vector(-100, 0), 50, 70, new p5.Vector(0, 0), 1);
var wall1 = new Wall(new p5.Vector(100, -100), 50, 50);
var collision = false;
var jump = new p5.Vector(0, -10);

function setup() {
    createCanvas(1000, 500);
    background(100);
}

function draw() {
    // Set zero-point
    translate(-p1.pos.x * 0.95 + 100, height - p1.height);

    // Apply gravity if p1 is not touching object
    if (p1.pos.y > 0) {
        // Do not apply p1.grav
        collision = true;
    } else {
        p1.pos.add(p1.grav);
        collision = false;
    }

    noStroke();
    fill(55, 37, 73);
    background(100);
    rect(p1.pos.x, p1.pos.y, p1.width, p1.height);
    rect(wall1.pos.x, wall1.pos.y, wall1.width, wall1.height);

    if (p1.pos.x < -p1.width * 2) {
        p1.velocity.x = 10;
        p1.pos.add(p1.velocity.x);
    } else {
        if (keyIsDown(LEFT_ARROW)) {
            p1.velocity.x = 5;
            p1.pos.sub(p1.velocity.x);
        } else if (keyIsDown(RIGHT_ARROW)) {
            p1.velocity.x = 5;
            p1.pos.add(p1.velocity.x);
        }
    }
}

function keyPressed() {
    if (key == ' ') {
        p1.pos.y += jump.y;
    }
}

所以最终的keyPressed()函数就是问题所在。每当用户按下空格时,我希望玩家“跳”,基本上为对象添加y速度。它现在所处的状态是简化的,它基本上将位置设置为jump.y。 (它现在似乎没有用,这很奇怪,因为它之前做过。)问题得到了解决。

无论如何,这不是主要问题。主要的问题是(当它工作时),跳转根本不会动画,并且基本上只是改变了p1对象的位置,正如我之前描述的那样(以及它应该如何工作,因为代码就是现在),但我最终希望跳转成为一个更好的动画,类似于“行走”动画,它相当流畅。

我已尝试用{/ p>之类的内容替换p1.pos.y += jump.y;

p1.velocity.y = jump.y;
p1.pos.y += p1.velocity.y;

但我得到了类似的结果。

我认为这可能是因为draw()函数是重复的,keyPressed()函数不是。我也尝试将函数放在draw()中,但这不起作用。

我真的迷失在这里。

编辑:Made an MCVE

1 个答案:

答案 0 :(得分:2)

你需要做一些事情:

第1步:如果你想让东西掉下来,你就需要引力。您可以将重力视为向下加速,在您的代码中,将velocity.y减少一些常数。当然,您还必须将此velocity.y实际添加到玩家动作中。现在你只需添加velocity.x

第2步:如果你想要停止掉落的东西,你将需要一些阻止玩家向下移动的逻辑。这可以像检查玩家的Y位置一样简单,也可以更高级,并检查游戏对象。在任何情况下,你都必须实施阻止你从屏幕上掉下来的东西。

第3步:完成这两项操作后,您只需将keyPressed()值设置为某个值即可修复velocity.y功能。您可能还需要在这里办理登机手续以防止玩家在空中跳跃。

故事的寓意是:你必须将问题分解为更小的步骤,然后一次处理其中一个步骤。如果您遇到困难,请发布MCVE,我们会从那里开始。祝你好运。

相关问题