[英]Why do bouncing Actors in my JavaScript browser game not work?
我想實現一個在太空中飛行的火箭,它會從傳入的流星雨中反彈。 目前我已經通過比較兩個演員的 x 和 y position 並在碰撞時交換他們的速度來實現它。 碰撞檢測和速度交換確實有效(由 console.log 證明),但在屏幕上它們有時只會反彈。
我試圖確保比較演員的速度對象不引用相同的 JavaScript object(使用cSpeedX
等)。
游戲是用 Pixi JS 構建的。
碰撞檢測function,為每個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;
}
}
});
移動 function 在火箭和流星上實現
this.move = (delta) => {
this.x += this.speed.x * delta;
this.y += this.speed.y * delta;
};
export const checkCollision = (current, objects) => {
objects.forEach((o) => {
if (current !== o) {
您還寫了: The collision detection function, executed for each actor (all meteroids and the rocket)
所以我想某處也有類似的循環:
objects.forEach((o) => {
checkCollision(o, objects);
});
這意味着對於每對對象,碰撞檢查兩次。
讓我們假設o1
和o2
是一些不同的對象,並且它們發生碰撞。 那時會發生什么? :
checkCollision(o1, objects); <-- swap speed between o1 and o2
...
checkCollision(o2, objects); <-- swap speed between o2 and o1
因此速度將在它們之間交換 2 次 - 換句話說:兩個對象的速度將保持不變。
要調查是否確實是這種情況,您可以像這樣放置console.log
(或打印對象 id 的東西):
if (dx < 0 && dy < 0) {
console.log('swapping speed of of objects:');
console.log(current);
console.log(o);
const cSpeedX = current.speed.x;
然后准備 2 個對象碰撞時的情況並檢查控制台日志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.