我刚开始使用p5.js,我喜欢简单但有一件事我无法理解。keyPressed()函数无法顺利跳转
我设置以下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
也想出了它为什么不跳跃,-10显然太小了一个明显的跳跃。y – YSbakker