undeadbytes

entityToPlayer(entity, game, { on, onDistance, onCallback })

The entityToPlayer method manages collisions between a given entity and the player in the game environment.

Parameters:

Logic:

  1. Determine Position Vectors:
    let vectorX = game.player.x - entity.x;
    let vectorY = game.player.y - entity.y;
    

    The method calculates the vector between the player and the entity’s current position.

  2. Handling Dead Player:
    if (game.player.dead) {
      vectorX = entity.lastVectorX;
      vectorY = entity.lastVectorY;
    } else {
      entity.lastVectorX = vectorX;
      entity.lastVectorY = vectorY;
    }
    

    If the player is dead, the entity’s position is set to their last known position; otherwise, the last known position is updated.

  3. Determine Distance:
    const distance = Collision.distance(vectorX, vectorY);
    

    The method calculates the distance between the player and the entity.

  4. Entity Type Check:
    if (onCallback && on === entity.type && distance <= onDistance) {
       onCallback();
    }
    

    If the entity type matches the passed callback object information and the distance to the player is within the trigger range, the optional callback function is executed.

  5. Enemy Type Check:
    if (distance > 0 && entity.type === 'enemy') {
    

    For enemy entities, the method proceeds if the distance to the player is greater than 0.

  6. Distance Check for Enemy:
    if (distance < 800) {
    

    If the distance to the player is less than 800, adjust the entity’s angle and position toward the player.

  7. Update Entity Position:
    entity.angle = Math.atan2(vectorY, vectorX) - 90 * Math.PI / 180;
    entity.x += vectorX * entity.speed;
    entity.y += vectorY * entity.speed;
    

    The entity’s angle and position are updated based on the vector between the player and the entity.

  8. Collision with Walls:
    const collisionVector = Collision.entityToWalls(entity, game.walls);
    entity.x += collisionVector.x * entity.speed;
    entity.y += collisionVector.y * entity.speed;
    

    The method checks for collisions with walls using entityToWalls and adjusts the entity’s position accordingly.

  9. Enemy Momentum Adjustment:
    entity.incrementer += entity.speed;
    entity.position = Math.sin(entity.incrementer * Math.PI / 180);
    

    The entity’s momentum is used to adjust the angle until it works its way around obstacles.

  10. Player Hurt Check:
    if (distance < 100 && entity.type === 'enemy') {
      game.player.takeDamage(entity);
    }
    

    If the distance to the player is less than 100, the player takes damage from the enemy.

Purpose:

The primary purpose of the entityToPlayer method is to handle collisions between a given entity and the player in the game environment. It ensures that entities respond realistically to the player’s presence, adjusting their positions, angles, and interactions based on distance and game context.