I want to have a weapon which is triggered on mouse click. When the bullet collides with one of the enemies I want it to be destroyed and the bullet also to be destroyed. The problem I’m facing right now - the bulled doesn’t get destroyed on collision. So it gets past one enemy, removing it, and then continues to remove enemies beyond the first one.
It can be fixed by checking that collide already happened and not firing it again but then of course collide doesn’t work more than once and more enemies can not de destroyed. But even in that case bullet is not destroyed.
And if I click mouse button a lot of times the game start to lag. I don’t know if it is connected somehow, maybe something is getting created a bunch of times…
I have a group of enemies which gets created in create function
const createAlien = ({ scene }) => {
const aliens = scene.physics.add.group();
let alien;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 4; j++) {
alien = scene.add.circle(300 + i * 20, 100 + j * 20, 5, 0xabcdef);
aliens.add(alien);
}
}
return aliens;
};
Then I have a function in update function like this
export const shoot = ({ scene }) => {
scene.input.on('pointerdown', pointer => {
if (pointer.button === 0) {
weapon({
scene,
fromX: playerObj.x,
fromY: playerObj.y,
toX: pointer.position.x,
toY: pointer.position.y,
aliens: globalEnemy,
});
}
});
};
An in my weapon function
export const createWeapon = ({ scene }) => {
globalScene = scene;
};
const weapon = ({ scene, fromX, fromY, toX, toY, aliens }) => {
const weaponPhysicsGroup = globalScene.physics.add.group({});
const bullet = globalScene.add.circle(fromX, fromY, 2, 0xff0000);
weaponPhysicsGroup.add(bullet);
const delta = Math.sqrt(Math.pow(toX - fromX, 2) + Math.pow(toY - fromY, 2));
const velocityX = (speed / delta) * (toX - fromX);
const velocityY = (speed / delta) * (toY - fromY);
weaponPhysicsGroup.setVelocity(velocityX, velocityY);
globalScene.physics.add.collider(weaponPhysicsGroup, aliens, (b, alien) => {
// console.log('hit')
colliderActivated = false;
bullet.destroy();
b.destroy();
alien.destroy();
updateScore(10);
});
setTimeout(() => bullet.destroy(), 1000);
};
the full code here
All the help will be appreciated.
UPDATE
I fixed everything by calling my shoow function not in update but in create.