Enemy AI script for 2D platformer
Hello!
I'm trying to make a 2D platformer game and I wish to add an AI function to the game. The problem is that I don't really know how to make it work.
The AI is supposed to have the same functions as the Player, which is idle, walking and attacking.
Idle > player not within range of the enemy
Walking > player in range of the enemy
Attacking > enemy throws a ball at the player
I've been stuck with this problem for days and I would really like it if someone could help me out.
This is my current AI script. I know it is messy and all and that's why I would appreciate some help. I'm not very experienced at programming, and that's why I want to learn everything!
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Chase : MonoBehaviour
{
[SerializeField] private float m_MaxSpeed = 10f; // The fastest the player can travel in the x axis.
[SerializeField]
private GameObject tomatoPrefab;
private Animator m_Anim; // Reference to the player's animator component.
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private void Awake()
{
// Setting up references.
m_Anim = GetComponent<Animator>();
m_Rigidbody2D = GetComponent<Rigidbody2D>();
}
public void Move(float move, bool crouch, bool jump)
{
if (Input.GetKeyDown (KeyCode.E)) {
ThrowTomato(0);
}
{
// The Speed animator parameter is set to the absolute value of the horizontal input.
m_Anim.SetFloat("Speed", Mathf.Abs(move));
// Move the character
m_Rigidbody2D.velocity = new Vector2(move*m_MaxSpeed, m_Rigidbody2D.velocity.y);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
public void ThrowTomato(int value)
{
if (m_FacingRight) {
GameObject tmp = (GameObject)Instantiate (tomatoPrefab, transform.position, Quaternion.identity);
tmp.GetComponent<Tomato>().Initialize(Vector2.right);
} else {
GameObject tmp = (GameObject)Instantiate (tomatoPrefab, transform.position, Quaternion.identity);
tmp.GetComponent<Tomato>().Initialize(Vector2.left);
}
}
}
}
And this is my object throw script (attack):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Tomato : MonoBehaviour {
[SerializeField]
private float speed;
private Rigidbody2D myRigidbody;
private Vector2 direction;
// Use this for initialization
void Start () {
myRigidbody = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
myRigidbody.velocity = direction * speed;
}
// Update is called once per frame
void Update () {
}
public void Initialize(Vector2 direction)
{
this.direction = direction;
}
void OnBecameInvisible()
{
Destroy(gameObject);
}
}
Answer by ericbegue · Jan 08, 2017 at 03:17 PM
Programming AIs without a methodology or a framework can easily lead to write complicated code. A common AI technique to implement simple AIs is Finite State Machine (FSM). Using and FSM you define your AI as a set of states and a set of transitions. You can directly implement a FSM in c# using an enum to list the states and a switch case to define what to in each state, and how to transition to the next state.
A more advanced tool is Behaviour Tree, which does a good job for implementing complex AIs. Have a look at Panda BT (www.pandabehaviour.com). It's a scripting framework based on Behaviour Tree. Using this tool, your AI could be written as:
tree("root")
fallback
tree("AttackPlayer")
tree("ApproachPlayer")
tree("Idle")
tree("AttackPlayer")
while IsPlayerInAttackRance
sequence
AimAt_Player
ThrowBall
tree("ApproachPlayer")
while
sequence
IsPlayerVisible
not IsPlayerInAttackRance
sequence
SetDestination_Player
MoveTo_Destination
tree("Idle")
while not IsPlayerVisible
DoNothing
The package contains several examples from simple to advanced, demonstrating how the tool works and how it can be used. If you have any question about using this tool, you are welcome on this forum thread.
Your answer
Follow this Question
Related Questions
Fixing enemy behavior state machine in Unity 0 Answers
How to make an npc/ai walk next to the player? (C#) 1 Answer
How to get in enemy to stop after a certain distance from the player? 0 Answers
Get player and enemy hit bars to respond to each others attack not their own 1 Answer
Best way of moving player 2 Answers