Hello,
I want to implement a very basic cover system for the AI in my game. I’ve based this on a system of “Cover Slots”, which are placed around the level, surrounding specific objects that can act as cover.
In the situation that the player begins to fire on an enemy, I want that enemy to be able to move to the nearest cover slot that provides protection from the player’s position:
The box represents a cover object, the circles represent cover slots. The player is at the top, and the AI enemy is at the bottom.
Currently, my code is as follows:
/// <summary>
/// Finds the nearest cover slot that provides cover against a certain position (e.g. where an enemy character is).
/// </summary>
/// <param name="positionToTakeCoverFrom"></param>
/// <param name="position"></param>
/// <returns></returns>
public CoverSlot FindNearestCoverSlotProvidingCoverAgainstPosition(Vector3 positionToTakeCoverFrom, Vector3 position)
{
// Find the nearest cover slots.
var coverSlots = FindSceneObjectsOfType(typeof (CoverSlot)) as CoverSlot[];
IOrderedEnumerable<CoverSlot> coverSlotsInDistanceOrder =
coverSlots.OrderBy(
slot =>
Vector3.Distance(new Vector3(position.x, 0, position.z),
new Vector3(slot.transform.position.x, 0, slot.transform.position.z)));
// Get the direction data.
Vector3 directionBetweenPositions = (positionToTakeCoverFrom - position).normalized;
// Filter those in the wrong direction.
return
coverSlotsInDistanceOrder.First(
slot =>
(new Vector3(positionToTakeCoverFrom.x, 0, positionToTakeCoverFrom.z) -
new Vector3(slot.FacingDirection.x, 0, slot.FacingDirection.z)).normalized == directionBetweenPositions);
}
I can see that it would not work, due to the last part being too “specific” (correct wording?). On debugging, I’m also a little bit confused about how 3 cover slots can all have the same normalised direction vector. See below:
The bottom vector represents the direction between the enemy AI object and the player object (at the top of the screen, behind the cover box). The top vector is equal for all three of the cover slots (the 3 cubes next to the cover box). This confuses me, as the direction between each slot and the player object is clearly different.
Can anybody suggest the best way to implement this?
Thanks,
Richard

