【发布时间】:2021-03-30 01:04:29
【问题描述】:
我在理解和解决我遇到的问题时遇到了问题。我有一个碰撞图,如果一个元素是 1,它应该触发我的碰撞检测功能,它确实如此。我很确定我的问题存在于我如何控制我的角色移动,但我不知道该怎么做才能解决它。即使我将player.vx 设置为0,如果我撞到了墙,我仍然可以穿过它。然后我添加了player.x = cell.x - cell.w,但是对所有方面都这样做会导致角色被抛来抛去,具体取决于我的路由表中首先调用哪一方面。
我还尝试了许多增加播放器速度的变体,以防止不必要的穿透。
这是我的玩家代码
let friction = 0.9;
let gravity = 2;
let size = 32;
//player
class Player {
constructor() {
this.x = 256;
this.y = 96;
this.w = 32;
this.h = 32;
this.vx = 0;
this.vy = 0;
this.oldX = this.x;
this.oldY = this.y;
this.jumping = false;
}
draw() {
ctx.fillStyle = 'green';
ctx.fillRect(this.x, this.y, this.w, this.h)
}
update() {
this.oldX = this.x;
this.oldY = this.y;
if (controller.right) {this.vx += 1}
if (controller.left) {this.vx -= 1}
if (controller.up && !this.jumping) {this.vy -= 10; this.player = true}
if (controller.down) {this.vy += 1}
this.x += this.vx;
this.y += this.vy;
this.vx *= friction;
this.vy *= friction;
this.vy += gravity;
this.draw();
}
}
let player = new Player();
还有一个 Codepen,以便更轻松地帮助https://codepen.io/jfirestorm44/pen/GRrjXGE?editors=0010
提前致谢
编辑:如果有人发现这一点,我在下面的 cmets 中留下了一个新的 CodePen,并带有一个完全重写的工作示例。
【问题讨论】:
标签: javascript collision-detection game-physics