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 stebongo · Dec 18, 2016 at 03:56 PM · c#aiissue

Issue with basic enemy AI script.

Code:

 using UnityEngine;
 using System.Collections;
 
 public class enemyAI : MonoBehaviour
 {
     private Rigidbody2D myRigidbody;
     private bool moveRight;
     private Vector2 moveLocation;
     [SerializeField]
     private float speed;
     [SerializeField]
     private Vector2 tra1;
     [SerializeField]
     private Vector2 tra2;
     // Use this for initialization
     void Start()
     {
         myRigidbody = GetComponent<Rigidbody2D>();
         moveRight = true;
         
     }
 
     // Update is called once per frame
     void FixedUpdate () {
         
         Debug.Log(moveRight);
         tra1 = transform.position;
 
         EmemyMovement();
         
 
         tra2 = transform.position;
 
         if (tra1.x == tra2.x)
         {
             moveRight = !moveRight;
         }
     }
 
 
     private void EmemyMovement()
     {
         if (moveRight == true)
         {
             moveLocation = new Vector2(transform.position.x + speed, transform.position.y);
             myRigidbody.MovePosition(moveLocation);
         }
         else
         {
 
             moveLocation = new Vector2(transform.position.x + -speed, transform.position.y);
             myRigidbody.MovePosition(moveLocation);
         }
     }
 }


It should be that it moves right until it stops then it moves left but when I run it the variable moveRight changes between true and false every frame and bounces forwards and backwards. Any help?

Comment
Add comment · Show 3
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
avatar image Pengocat · Dec 18, 2016 at 04:15 PM 0
Share

"...moves right until it stops..." could you be more specific than that? You are setting tra1 and tra2 to the same position and then asking if they are the same. This is always going to be the same so the bool moveRight will always be flipped.

         tra1 = transform.position;
 
         Ememy$$anonymous$$ovement();
 
 
         tra2 = transform.position;
 
         if (tra1.x == tra2.x)
         {
             moveRight = !moveRight;
         }
avatar image stebongo · Dec 18, 2016 at 04:19 PM 0
Share

@Pengocat I mean it would move right until it hit a wall and couldn't move anymore. What is supposed to happen is that tra1 is checked, the enemy moves right then tra2 is checked. If the moving was successful the bool isn't flipped and if the rigidbody movement didn't go anywhere the bool is flipped.

Sorry if I was unclear.

avatar image Pengocat stebongo · Dec 18, 2016 at 05:59 PM 0
Share

Perhaps you can use something like this in some way. It goes towards the current waypoint then when close it picks the other waypoint. It is a big rough but it works.

 public float speed = 250f;
 public Transform waypointPositionA;
 public Transform waypointPositionB;
 Rigidbody2D myRigidbody;
 Vector3 direction;
 enum Waypoint
 {
     A,
     B
 }
 Waypoint currentWaypoint = Waypoint.A;

 void Start()
 {
     myRigidbody = GetComponent<Rigidbody2D>();
 }

 void FixedUpdate()
 {
     Ememy$$anonymous$$ovement();
 }

 void Ememy$$anonymous$$ovement()
 {
     // If close to A switch direction towards waypoint B
     if (Vector2.Distance(transform.position, waypointPositionA.position) < 0.1f && currentWaypoint != Waypoint.B)
     {
         currentWaypoint = Waypoint.B;
         // Instantly stop the rigidbody to change direction rapidly
         myRigidbody.velocity = Vector2.zero;
     }
     // If close to B switch direction towards waypoint A
     else if (Vector2.Distance(transform.position, waypointPositionB.position) < 0.1f && currentWaypoint != Waypoint.A)
     {
         currentWaypoint = Waypoint.A;
         myRigidbody.velocity = Vector2.zero;
     }
     // Calculate the vector towards current set waypoint
     switch (currentWaypoint)
     {
         case Waypoint.A:
             direction = (waypointPositionA.position - transform.position).normalized;
             break;
         case Waypoint.B:
             direction = (waypointPositionB.position - transform.position).normalized;
             break;
     }
     // $$anonymous$$ove the rigidbody towards the waypoint
     myRigidbody.AddForce(direction * speed * Time.fixedDeltaTime);
 }

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by ericbegue · Dec 18, 2016 at 06:18 PM

You want the AI to move back and forth between two walls? Here is a simplication of your script, with some comments:

 using UnityEngine;
 using System.Collections;
 
 public class EnemyAI : MonoBehaviour
 {
 
     // Note: public variables are serialize by default.
     public float speed = 1.0f;
     public Vector2 leftWall;
     public Vector2 rightWall;
 
     Vector3 direction;
 
     // Use this for initialization
     void Start()
     {
         direction = Vector3.right;
     }
 
     // Update is called once per frame
     void FixedUpdate()
     {
         Vector3 velocity = speed*direction;
 
         // Don't forget Time.Delta time to make the movement frame-rate independent.
         transform.position += velocity * Time.deltaTime; 
 
         if (transform.position.x > rightWall.x)
         {
             transform.position = rightWall;
             direction = Vector3.left;
         }
 
         if (transform.position.x < leftWall.x)
         {
             transform.position = leftWall;
             direction = Vector3.right;
         }
     }
 
 }
 

If you want to make more advanced AI, I would suggest to have a look at Behaviour Tree. It's an AI technique that simplifies the development of complex (or simple) AI. I've made a scripting framework based on Behaviour Tree ( see Panda BT: www.pandabehaviour.com ).

Developing AIs using this tool consist of defining "tasks" and use them from a BT script. For instance, to make an AI that move to arbitrary locations, you first need to make a "task" to handle the AI movement. This is implemented as a function on a MonoBehaviour:

 using UnityEngine;
 using Panda; // We are using Panda BT
 
 public class EnemyAIBT : MonoBehaviour
 {
     public float speed = 1.0f;
 
     public Transform[] locations; // Array of locations.
 
     Vector3 destination;
 
     [Task] // <-- This marks a function as a task.
     void MoveTo(int locationIndex)
     {
         // Set the destiantion when the task is starting.
         if (Task.current.isStarting)
             destination = locations[locationIndex].position;
 
         // Move towards the destination on each tick (Update).
         transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
 
         // The task is done when we have reached the destination.
         if (transform.position == destination) 
             Task.current.Succeed();
     }
 }
 

Once, you've defined some tasks, you can use them as building blocks from a BT script to define how your AI behaves. For instance, to make an AI that move back and forth between the first 2 locations, its BT script would be:

 tree("Root")
     sequence
         MoveTo(0)
         MoveTo(1)
 

This is an extremely simple BT, but you can do much more with Behaviour Tree. The package contains several examples from simple to advanced.

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

294 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

Related Questions

SetDirty won't work on Nested List 1 Answer

unity3d 5 game on fullscreen shows only half of game screen 4 Answers

Enemy watches player and shoots but bullets will not project 0 Answers

How do I make an AI(cube) that follows and rams the player? 0 Answers

A little doubt about creating a Talking BOT that simulates AI, for iOS system using Unity. 0 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