gpt4 book ai didi

javascript - keyPressed() 函数无法顺利渲染跳转

转载 作者:行者123 更新时间:2023-12-02 13:46:03 24 4
gpt4 key购买 nike

我刚刚开始使用 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 对象的位置,正如我之前所描述的(以及它应该如何工作,就像现在的代码一样),但我最终希望跳跃是一个更好的动画,类似于“行走”动画,相当流畅。

我已经尝试用类似的内容替换 p1.pos.y += Jump.y;

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

但我得到了类似的结果。

我认为这可能是因为 draw() 函数是重复的,而 keyPressed() 函数不是。我还尝试将该函数放入 draw() 内部,但这不起作用。

我真的迷路了。

编辑:Made an MCVE

最佳答案

您需要一些东西:

第 1 步:如果你想让东西下落,你就需要重力。您可以将重力视为向下的加速度,在您的代码中,速度将按某个常数减小 velocity.y。当然,您还必须实际将此 velocity.y 添加到玩家运动中。现在您只需添加 velocity.x

第 2 步:如果您希望物体停止掉落,您将需要一些逻辑来阻止玩家向下移动。这可以像检查玩家的 Y 位置一样简单,或者您可能会更高级并检查游戏对象。无论如何,你都必须采取一些措施来防止你从屏幕上掉下来。

第 3 步:完成这两件事后,您只需设置 velocity.y 值即可修复 keyPressed() 函数到某个值。您可能还需要在此处进行检查以防止玩家在空中跳跃。

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

关于javascript - keyPressed() 函数无法顺利渲染跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com