Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by GoBlaze · Jan 08, 2017 at 07:35 AM · c#playeraifollownpc

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);
     }
 }
 





Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

308 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges