handle collisions

This commit is contained in:
Mylloon 2022-11-27 18:09:56 +01:00
parent 0437902699
commit 04d6187401
Signed by: Anri
GPG key ID: A82D63DFF8D1317F
2 changed files with 73 additions and 6 deletions

View file

@ -102,21 +102,30 @@ export class Env {
* Animate all the entities in the environnement
*/
animate = () => {
// Retrieve ennemies
const ennemies = this.elements
.filter((entityData) => entityData[1] == TypeEntity.ennemy)
.map((ennemyData) => ennemyData[0]);
// Player animation
this.elements
.filter((entityData) => entityData[1] == TypeEntity.player)
.map((playerData) => playerData[0])
.forEach((player) => {
if (player.animation) {
player.animation();
if (
!player.animation(ennemies.map((object) => object.data))
) {
// If animation returned false, the player died!
console.log("player died!");
// TODO: Stop the game
// Destroy the player?
// End game
}
}
});
// Enemy animation
const ennemies = this.elements
.filter((entityData) => entityData[1] == TypeEntity.ennemy)
.map((ennemyData) => ennemyData[0]);
ennemies.forEach((ennemy) => {
ennemy.data.position.x -= 0.05;
if (ennemy.data.position.x <= -10) {

View file

@ -11,7 +11,12 @@ export class Player extends Cube {
this.movementData = new Rotation(this.data.position);
}
animation = () => {
/**
* Play the player animation
* @param {*} listEnnemies
* @returns boolean if the player is alive or not
*/
animation = (listEnnemies) => {
// If we jump
if (this.movementData.state) {
// Rotation
@ -43,8 +48,14 @@ export class Player extends Cube {
this.movementData.changeState();
}
}
return !this.checkCollision(listEnnemies);
};
/**
* Handle player's input
* @param {string} key key pressed
*/
controlUser = (key) => {
const now = Date.now();
if (
@ -59,4 +70,51 @@ export class Player extends Cube {
this.movementData.changeState(now);
}
};
/**
* Check collisions with ennemies
* @param {*} listEnnemies
* @returns boolean
*/
checkCollision = (listEnnemies) => {
for (
let vertexIndex = 0;
vertexIndex < this.data.geometry.attributes.position.array.length;
vertexIndex++
) {
// Retrieve the vertex from the player geometry
const localVertex = new THREE.Vector3()
.fromBufferAttribute(
this.data.geometry.attributes.position,
vertexIndex
)
.clone();
// Apply the player matrix for the vector
const globalVertex = localVertex.applyMatrix4(this.data.matrix);
// Substract the position from it
const directionVector = globalVertex.sub(this.data.position);
// Create the raycaster for this vector from the player position
const ray = new THREE.Raycaster(
this.data.position,
directionVector.clone().normalize()
);
// Check if the raycaster hit ennemies
const collisionResults = ray.intersectObjects(listEnnemies, false);
if (
collisionResults.length > 0 &&
directionVector.length() < 1.5 &&
collisionResults[0].distance < directionVector.length()
) {
// Yes some ennemies are in the way
return true;
}
}
// No ennemies found
return false;
};
}