Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 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 /
  • Help Room /
avatar image
0
Question by CraftyMaelyss · Sep 07, 2016 at 02:33 PM · c#aichase

How do I make an enemy chase the player with a C script?

Basically I've been searching this for ages and the techniques and scripts I've seen and tried haven't been able to work, so this is why I'm asking here.

How do I write a script so that when the player walks within a certain range, the enemy will start to chase them but when they're further away, they will just look in their direction?

Again I've been through the answers, I've googled this topic and read through a lot of forums and I still can't seem to get it to work. This is one of the scripts that I tried to use from a tutorial(that didn't work) so maybe someone can see where I've gone wrong?

using UnityEngine; using System.Collections;

public class FogMan : MonoBehaviour { var target : Transform; //the enemy's target var moveSpeed = 3; //move speed var rotationSpeed = 3; //speed of turning var range : float=10f; var range2 : float=10f; var stop : float=0; var myTransform : Transform; //current transform data of this enemy function Awake() { myTransform = transform; //cache transform data for easy acces/performance }

 function Start()
 {
     Target = GameObject.FindWithTag("Basehuman01b").transform; //target the player

 }

 function Update () {
     //rotate to look at the player
     var distance = Vector3.Distance(myTransform.position, target.position);
     if (distance<=range2 && distance>=range){
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
             Quaternion.LookRotation(target.position -- myTransform.position), rotationSpeed*Time.deltaTime);
     }


     else if(distance<=range && distance>stop){

         //move towards the player
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
             Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
         myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
     }
     else if (distance<=stop) {
         myTransform.rotation = Quaternion/Slerp(myTransform.rotation,
             Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     }

 }
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

3 Replies

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

Answer by metalted · Sep 07, 2016 at 03:29 PM

I'm just going to approach this problem from scratch and try to meet the specs in as little code as possible. You ask for an enemy that will follow a player from a certain distance, and will always look at it.

C#:

 //The target player
 public Transform player;
 //At what distance will the enemy walk towards the player?
 public float walkingDistance = 10.0f;
 //In what time will the enemy complete the journey between its position and the players position
 public float smoothTime = 10.0f;
 //Vector3 used to store the velocity of the enemy
 private Vector3 smoothVelocity = Vector3.zero;

 //Call every frame
 void Update()
 {
     //Look at the player
     transform.LookAt(player);
     //Calculate distance between player
     float distance = Vector3.Distance(transform.position, player.position);
     //If the distance is smaller than the walkingDistance
     if(distance < walkingDistance)
     {
         //Move the enemy towards the player with smoothdamp
         transform.position = Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime);
     }
 }

Javascript:

 //The target player
 public var player : Transform;
 //At what distance will the enemy walk towards the player?
 public var walkingDistance : float = 10.0f;
 //In what time will the enemy complete the journey between its position and the players position
 public var smoothTime : float = 10.0f;
 //Vector3 used to store the velocity of the enemy
 private var smoothVelocity : Vector3 = Vector3.zero;

 //Call every frame
 function Update()
 {
     //Look at the player
     transform.LookAt(player);
     //Calculate distance between player
     distance = Vector3.Distance(transform.position, player.position);
     //If the distance is smaller than the walkingDistance
     if(distance < walkingDistance)
     {
         //Move the enemy towards the player with smoothdamp
         transform.position = Vector3.SmoothDamp(transform.position, player.position, smoothVelocity, smoothTime);
     }
 }

Comment
Add comment · Show 8 · 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 CraftyMaelyss · Sep 08, 2016 at 09:52 AM 0
Share

@metalted How do I stop the enemy from going through solid objects? He's following them now, exactly how I wanted but he seems to phase right through physical objects(and I checked, they all have mesh colliders) so how do I stop him from doing that?

avatar image CraftyMaelyss · Oct 18, 2016 at 01:34 PM 0
Share

@metalted I applied this script to a small animated butterfly that I created but it goes straight to the player's feet when it's original position is a few feet off the ground, how do I fix this?

Property of Crafty$$anonymous$$aelyss

buttersplat2.png (115.2 kB)
avatar image metalted · Oct 19, 2016 at 01:35 PM 0
Share

A possibility is to create a class variable to store the y position of your butterfly in.

Then in the start method, assign the y position to the variable or set the value manually if that is what you prefer.

If you look at the code, the part of the Vector3.SmoothDamp(...) will move the transform to the target position. Because we use a Vector3, this will affect the x y and z position. To keep the y position at a constant value, you need to alter the Vector3. The parts you need to paste in will look something like this:

float yPosition;

Void Start(){ yPosition = transform.position.y; }

Void Update{ ... Vector3 wantedPosition = new Vector3(player.position.x, yPosition, player.position.z);

//Now the transform will only move in the xz plane. Enter this into your SmoothDamp:

transform.position = Vector3.SmoothDamp(transform.position, wantedPosition,....);

}

You can do this with the x y and z coordinates to make sure that they dont change. If you only want to change the x position for example, you can just lock the y and z.

avatar image CraftyMaelyss metalted · Oct 20, 2016 at 06:15 AM 0
Share

I've tried it but I'm getting errors, this is what my script looks like after trying to add in the additional code:

using UnityEngine; using System.Collections;

public class Butterflies : $$anonymous$$onoBehaviour {

 // Use this for initialization
 void Start () {

 }
     //The target player
     public Transform Basehuman01b;
     //At what distance will the enemy walk towards the player?
     public float walkingDistance = 10.0f;
     //In what time will the enemy complete the journey between its position and the players position
     public float smoothTime = 10.0f;
     //Vector3 used to store the velocity of the enemy
     private Vector3 smoothVelocity = Vector3.zero;
     
     //Call every frame
     void Update()
     {
         //Look at the player
         transform.LookAt(Basehuman01b);
         //Calculate distance between player
     float distance = Vector3.Distance(transform.position, Basehuman01b.position);
         //If the distance is smaller than the walkingDistance
         if(distance < walkingDistance)
             {
                 //$$anonymous$$ove the enemy towards the player with smoothdamp
         transform.position =     transform.position = Vector3.SmoothDamp(transform.position, wantedPosition,....);

         float yPosition;
         { yPosition = transform.position.y; }
         { ... Vector3 wantedPosition = new Vector3(Basehuman01b.position.x, yPosition, Basehuman01b.position.z);
     
         }
     }
 }

Have I just entered this new code in the wrong area of the script?

avatar image metalted · Oct 20, 2016 at 12:55 PM 0
Share

//The target player public Transform player; //At what distance will the enemy walk towards the player? public float walkingDistance = 10.0f; //In what time will the enemy complete the journey between its position and the players position public float smoothTime = 10.0f; //Vector3 used to store the velocity of the enemy private Vector3 smoothVelocity = Vector3.zero;

//Y position of the transform private float yPosition;

void Start(){ yPosition = transform.position.y; }

//Call every frame void Update() { //Look at the player transform.LookAt(player); //Calculate distance between player float distance = Vector3.Distance(transform.position, player.position);

  //Calculate the new Vector3 
 Vector3 wantedPosition = new Vector3(player.position.x, yPosition, player.position.z);

  //If the distance is smaller than the walkingDistance
  if(distance < walkingDistance)
  {
      //$$anonymous$$ove the enemy towards the player with smoothdamp
      transform.position = Vector3.SmoothDamp(transform.position, wantedPosition, ref smoothVelocity, smoothTime);
  }

}

avatar image metalted · Oct 20, 2016 at 12:58 PM 0
Share

Sorry for the bad comment, im trying to help you as quickly as possible but it turns out i cant select the text and change it to code on my phone. So try to piece it together the right way. If its impossible for you, ill edit it at a later time.

avatar image CraftyMaelyss metalted · Oct 22, 2016 at 08:06 AM 0
Share

I'm still getting errors from it :(

Show more comments
avatar image
0

Answer by bonez9oh5 · May 08, 2017 at 06:52 AM

@CraftyMaelyss Does your enemy have a collider and rigid body attached? that could be why its passing through objects.

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 CraftyMaelyss · May 09, 2017 at 02:47 AM 0
Share

@bonez9oh5 Well whenever I try to attach a rigidbody, it causes some (hilarious) glitches but it definitely has a collider.

avatar image
0

Answer by eshedye · Jan 23, 2018 at 09:25 PM

how do i make it faster?

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

8 People are following this question.

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

Related Questions

How do I get my AI to chase the player?,How do I go from patrolling to chasing the player? 3 Answers

AI being scared of player. 0 Answers

Enemy AI using pathfinding to avoid obstacles 1 Answer

Why does my enemy teleport to my player? 2 Answers

Problems with Enemy AI with Raycasts 1 Answer


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