I want to implement a rocket flying through space, which bounces off from incoming meteroids. Currently I have implemented it by comparing the x and y position of both actors and swapping their speeds on collision. The detection of a collision and the speed swapping does work (proved by console.log), however on the screen they only sometimes bounce off.
I tried to make sure that the speed objects of the compared actors do not reference the same JavaScript object (with cSpeedX etc).
The game is built with Pixi JS.
The collision detection function, executed for each actor (all meteroids and the rocket)
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;
}
}
});
The move function implemented both on the rocket and meteroids
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) {
You wrote also: The collision detection function, executed for each actor (all meteroids and the rocket)
so i suppose somewhere there is also loop like:
objects.forEach((o) => {
checkCollision(o, objects);
});
This would mean that for every pair of objects the collision is checked twice.
Lets assume that o1 and o2 are some different objects, and that they collide. What will happen then? :
checkCollision(o1, objects); <-- swap speed between o1 and o2
...
checkCollision(o2, objects); <-- swap speed between o2 and o1
So speed will be swapped 2 times between them - in other words: speed of both objects will remain the same.
To investigate if this is indeed the case you can put console.log (or something to print id of object) like this:
if (dx < 0 && dy < 0) {
console.log('swapping speed of of objects:');
console.log(current);
console.log(o);
const cSpeedX = current.speed.x;
Then prepare situation when 2 objects collide and check console logs.