entityToWalls(entity, walls)
The entityToWalls
method is responsible for handling collisions between a given entity and an array of walls in the game environment.
entity
(Object): The entity for which collisions are being checked.walls
(Array): An array containing the wall entities in the game.const result = {
x: 0,
y: 0
};
The method initializes a result object to store the cumulative collision vectors along the x and y axes.
for (let i = 0; i < walls.length; i++) {
const wall = walls[i];
The method iterates through each wall in the array.
if (Collision.arcBoxCollision({
arcX: entity.x,
arcY: entity.y,
wallX: wall.x,
wallY: wall.y,
size: config.cell.size,
radius: config.cell.radius,
})) {
It checks for collision between the arc-shaped entity and the rectangular wall using the arcBoxCollision
method.
const wallCenterX = wall.x + config.cell.size / 2;
const wallCenterY = wall.y + config.cell.size / 2;
let vectorX = entity.x - wallCenterX;
let vectorY = entity.y - wallCenterY;
const distance = Collision.distance(vectorX, vectorY);
If a collision is detected, the method calculates the vector between the center of the wall and the entity, along with the distance between them.
if (distance > 0) {
vectorX /= distance;
vectorY /= distance;
result.x += vectorX;
result.y += vectorY;
}
The method updates the cumulative collision vectors based on the normalized vector between the entity and the wall.
return result;
Finally, the method returns the cumulative collision vectors, which will be used to adjust the entity’s position to avoid collisions with walls.
The primary purpose of the entityToWalls
method is to handle collisions between an entity and an array of walls in the game environment. It utilizes the arcBoxCollision
method to check for collisions with each wall individually, and the cumulative collision vectors are then used to adjust the entity’s position.
This functionality is crucial for ensuring that entities navigate the game world realistically, responding to the presence of walls to prevent phasing through them.