【发布时间】:2022-01-17 06:22:15
【问题描述】:
我想实现一个在太空中飞行的火箭,它会从传入的流星体反弹。目前我已经通过比较两个演员的 x 和 y 位置并在碰撞时交换他们的速度来实现它。碰撞检测和速度交换确实有效(由 console.log 证明),但是在屏幕上它们有时会反弹。
我试图确保被比较的演员的速度对象不引用相同的 JavaScript 对象(cSpeedX 等)。
游戏是用 Pixi JS 构建的。
碰撞检测功能,为每个actor(所有流星和火箭)执行
export const checkCollision = (current, objects) => {
objects.forEach((o) => {
if (current !== o) {
const dx =
current.x < o.x
? o.x - o.width / 2 - (current.x + current.width / 2)
: current.x - current.width / 2 - (o.x + o.width / 2);
const dy =
current.y < o.y
? o.y - o.height / 2 - (current.y + current.height / 2)
: current.y - current.height / 2 - (o.y + o.height / 2);
if (dx < 0 && dy < 0) {
const cSpeedX = current.speed.x;
const cSpeedY = current.speed.y;
const oSpeedX = o.speed.x;
const oSpeedY = o.speed.y;
current.speed.x = oSpeedX;
current.speed.y = oSpeedY;
o.speed.x = cSpeedX;
o.speed.y = cSpeedY;
}
}
});
在火箭和流星雨上都实现了移动功能
this.move = (delta) => {
this.x += this.speed.x * delta;
this.y += this.speed.y * delta;
};
【问题讨论】:
标签: javascript browser pixi.js