Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 /
avatar image
1
Question by kopkinho · Feb 04, 2014 at 05:05 PM · 2daimovement scriptjavaescape

How to make a simple AI escape script?

I want to make a 2D game. I made scripts for controlling player and simple enemy movement. The enemies should flee from player. I check if player is near to enemy by Vector2.Distance and then make enemy's input equal to player's Input.GetAxis . But it doesn't work correctly and I know why. How to make enemy escape from player?

Comment
Add comment · Show 2
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 robertbu · Feb 04, 2014 at 05:32 PM 0
Share

We need to see your code and possibly a more detailed description of the desired behavior.

avatar image kopkinho · Feb 04, 2014 at 06:07 PM 0
Share

Here's the player script:

 #pragma strict
 
 var red: Transform;
 
 var speed: Vector2 = new Vector2(7,7);
 var distanceToRun: float = 2;
 
 private var movement: Vector2;
 
 function Update () {
     var inputX: float = Input.GetAxis("Horizontal");
     var inputY: float = Input.GetAxis("Vertical");
     
     var distanceFromRed = Vector2.Distance(this.transform.position, red.transform.position);
     
     var redSc: RedBallController = red.GetComponent("RedBallController");
     
     
     if (distanceFromRed < distanceToRun && inputX != 0 && inputY != 0)
         {
             redSc.inputX = inputX;
             redSc.inputY = inputY;
             redSc.speed = Vector2(4, 4);
         }
         else 
             {
                 redSc.inputX = -1;
                 redSc.inputY = 1;
                 redSc.speed = Vector2(0.5, 0.5);
             
             }
     
     
     movement = new Vector2(
         inputX*speed.x, 
         inputY*speed.y
     );
     
 
 }
 
 function FixedUpdate () {
     rigidbody2D.velocity = movement;
 }

The problem is that when Player walks away from Red Ball(enemy), it follows Player for a while. I know why. I can solve it by adding some IF and comparing input, but I think that there's more simple way to do it.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by TheRefoH · Feb 05, 2014 at 12:05 AM

You could add a collider to the enemy. Use a circle Collider and make it way bigger than your enemy is, than set it "is Trigger". If the player enters the Trigger then let the enemy run in the opposite direction. Its like a big bubble around the enemy and if something enters the bubble the enemy will run away. If the Player leavs the trigger it should stop the enemy from running away instantly.

This might not be the best solution but its a simple one in my opinion.

Comment
Add comment · Show 4 · 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
avatar image kopkinho · Feb 05, 2014 at 12:59 AM 0
Share

Thank you! I did something like that, with collider, but how to make enemy run in the opposite direction? How to check it?

avatar image TheRefoH · Feb 05, 2014 at 11:54 AM 0
Share

Since it´s a 2D game it should be enough to check the x and y Position of the Player, if the x,y Position is < than the x,y Position of the enemy then you have to increase the x,y of the enemy since this will get him further away. That would be the case if the player is on the left side of the enemy, it has to be the opposite if the player is on the right of the enemy.

I am not on my PC at the $$anonymous$$oment, but i think you can check the x and y position with "transform.position.x"

https://docs.unity3d.com/Documentation/ScriptReference/Transform-position.html

However since i am new to unity i dont know if this is a good solution. Furthermore will this only make your enemy run away on flat ground, if there are obstacles it wont make him jump over them. You maybe could combine it with your own code since the approach that you use for movement is way better.

avatar image kopkinho · Feb 05, 2014 at 03:40 PM 0
Share

Thank you, that works for me, but I used OnTriggerStay2D. But it's not smooth movement.

 function OnTriggerStay2D()
 {
  if (player.position.x < transform.position.x)
      {
         transform.position.x += Time.deltaTime * 10;
 
      }
     else transform.position.x -= Time.deltaTime * 10;
     
  if (player.position.y < transform.position.y)
      {
         transform.position.y += Time.deltaTime * 10;
 
      }
     else transform.position.y -= Time.deltaTime * 10;
 }
avatar image TheRefoH · Feb 05, 2014 at 06:26 PM 0
Share

I am glad I could help a bit. I dont know how to get the movement more smooth, but I am sure there is a way to do it :D

avatar image
0

Answer by 7Why · Jun 28, 2014 at 01:01 PM

Here's what i did;

 Vector3 playerPos;
 Vector3 ThisPos;
 GameObject Player;
 
 void Start ()
 {
     Player = GameObject.FindGameObjectWithTag("Player");
 }
 
 void Update ()
 {
     if (Player != null)
     {
         playerPos = Player.transform.position;
     }
 
     thisPos = transform.position;
 
     Collider2D[] collis = Physics2D.OverlapCircleAll(transform.position, minRange); // this creates a range so that when the player enters it the ai will tell it to move away
     foreach (Collider2D colli in collis){ 
         if (colli && colli.tag == "Player")
         { // if object has the right tag...
             transform.position = Vector2.Lerp(thisPos, -playerPos, Time.deltaTime * Speed); // this tells it to move toward the inverse of the players position.
         }
     }
 }
 


Hope this helps. make sure that you tag your player gameobject as "Player" otherwise it won't do anything.(Speed is the rate at which you want it to move its a Float value so just set to anything to begin with, you can fine tune it later.

Comment
Add comment · Show 1 · 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
avatar image BahamutZeRo · Oct 22, 2015 at 06:25 AM 0
Share

Hello 7Why, I did trying to use your code but the Inverse direction doesn't work very well thou. It's just keep moving to the left. If you are still around please guide me around. Peaace ^^

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

21 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

Related Questions

How to create a simple Enemy AI for a 2D game? Mine isn't working. . . 1 Answer

Help with 2D AI scripting 2 Answers

A* Pathfinding, destroying a path once it has reached its end 0 Answers

sprite changes z position without any input to do so 1 Answer

How to Rotate 2D Sprite Towards Moving Direction? 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