🎮

Beginner AI Behaviors in Unity

Apr 21, 2025

Blackthorne Prods: 5 Simple AI Behaviors in Unity

Overview

  • Focus: Beginner-friendly C# and Unity tutorial.
  • Objective: Create 5 simple but useful AI behaviors for game projects.
  • Promo: Courses available on making art, sound, and code for various game types.

AI Behaviors Covered

1. Follow Enemy AI

  • Behavior: Enemy follows a player character until a certain distance.
  • Implementation:
    1. Attach empty C# script to enemy character.
    2. Create variables:
      • public float: Speed of enemy.
      • public Transform: Target to follow.
      • public float: Minimum distance to stop.
    3. Update function:
      • Use Vector2.MoveTowards to move towards target.
      • Multiply speed with Time.deltaTime for frame-rate independence.
      • Use Vector2.Distance to check distance to stop moving.
    4. Optional attack code if close enough.

2. Shoot and Retreat Enemy

  • Behavior: Shoots projectiles and retreats when the player is close.
  • Implementation:
    1. Modify Follow Enemy script:
      • Use negative speed for retreating.
      • Retreat when distance is smaller than minimum.
    2. Shooting mechanism:
      • Create variables for projectile, time between shots, and next shot time.
      • Check time to shoot in Update function and instantiate projectile.
      • Manage shooting intervals.
    3. Projectile behavior:
      • Set target position to player.
      • Move towards target using Vector2.MoveTowards.
      • Destroy projectile on reaching target.

3. Patrolling Enemy

  • Behavior: Moves between predefined patrol points.
  • Implementation:
    1. Create variables:
      • Speed, array of Transforms for patrol points, wait time, and current point index.
    2. Use Vector2.MoveTowards to move to patrol points.
    3. Use coroutine to handle waiting at each patrol point.
    4. Loop patrol behavior by resetting patrol point index.
    5. Ensure coroutine only runs once per patrol point.

4. Obstacle Avoidance Enemy

  • Behavior: Moves towards target while avoiding obstacles.
  • Implementation:
    1. Use A* Pathfinding Algorithm with pre-made package.
    2. Setup scene with obstacles and target.
    3. Create grid graph for movement path.
    4. Configure pathfinding properties and avoid obstacles using layers.*

5. Line of Sight Enemy

  • Behavior: Detects player within a specific sight range.
  • Implementation:
    1. Rotate enemy with public rotation speed variable.
    2. Use Raycasts for line of sight detection.
    3. Create public variables for rotation speed and vision distance.
    4. Visualize raycasts with Debug.DrawLine.
    5. Handle line of sight using LineRenderer component.
    6. Modify colors based on detection status.

Conclusion

  • Encouragement to mix AI behaviors for unique compositions.
  • Emphasis on creativity and customization in AI development.
  • Call to action to check game development courses for comprehensive learning.