Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
2
Question by Conchness · Nov 24, 2012 at 09:27 PM · playerenemydistanceattackjittering

How to stop enemy within certain distance of player?

Hey I'm pretty new to Unity 3D & C sharp scripting. I was wondering how to stop the enemy from jittering against the player when within attacking distance (IE the enemy gets within attacking distance and stops 1 unit away) and also how do Istop the enemy from randomly moving up the screen when I press play. Here is my current script for the enemy ai

 using UnityEngine;
 using System.Collections;
 
 public class EnemyAI : MonoBehaviour {
     public Transform target;
     public int moveSpeed;
     public int rotationSpeed;
     public int maxdistance;
     public float attackTime;
     public float coolDown;
     private Transform myTransform;
 
     void Awake()
     { 
         myTransform = transform;
     }
     
 
     void Start () {
         GameObject go = GameObject.FindGameObjectWithTag("Player");
         target = go.transform;
         attackTime = 0;
         coolDown = 4.0f;
         }
 
     void Update () {
 
     
         Debug.DrawLine(target.position, myTransform.position, Color.red); 
         if (Vector3.Distance(target.position, transform.position) < 20)
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
 
         {
         myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
         }
             
         if(attackTime > 0)
         attackTime -= Time.deltaTime;
         
         if(attackTime < 0)
         attackTime = 0;
         
         if(attackTime == 0) {
         Attack();
         attackTime = coolDown;
         }
     }        
         private void Attack() {
         float distance = Vector3.Distance(target.transform.position, transform.position);
         Vector3 dir = (target.transform.position - transform.position).normalized;
         float direction = Vector3.Dot(dir, transform.forward);
         
         if(distance < 7) {
         if(direction > 0) { 
         PlayerHealth eh = (PlayerHealth)target.GetComponent("PlayerHealth");
         eh.AddjustCurrentHealth(-10);
             }
         }
     }
 }

Any help or hints will be greatly appreciated. Cheers :)

Comment
Add comment · Show 1
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 T27M · Nov 24, 2012 at 09:29 PM 0
Share

Use the code tags when posting your code otherwise it's almost unreadable, it's the button with the 10101 on it above the text box.

2 Replies

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

Answer by aldonaletto · Nov 25, 2012 at 01:03 AM

The if in Update seems wrong: it only controls the enemy rotation, turning to the player when closer than 20m - the enemy keeps going to the player no matter how far it is. Is it an intended feature? If not, you could change it and include the min distance this way:

 void Update () {
     Debug.DrawLine(target.position, myTransform.position, Color.red); 
     float dist = Vector3.Distance(target.position, transform.position);
     if (dist < 20){ 
         // get the target direction:
         Vector3 targetDir = target.position - myTransform.position;
         targetDir.y = 0; // kill any height difference to avoid tilting
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targetDir), rotationSpeed * Time.deltaTime);
         if (dist > 2){ // check min distance
             // only move to the target if farther than min distance
             myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
         }
     }
     if(attackTime > 0){
         attackTime -= Time.deltaTime;
         if (attackTime <= 0){
             Attack();
             attackTime = coolDown;
         }
     }
 }
   
 private void Attack() {
     float distance = Vector3.Distance(target.transform.position, transform.position);
     Vector3 dir = (target.transform.position - transform.position).normalized;
     float direction = Vector3.Dot(dir, transform.forward);
     if (distance < 7 && direction > 0){
        // the generic GetComponent is faster!
        PlayerHealth eh = target.GetComponent< PlayerHealth>();
        eh.AddjustCurrentHealth(-10);
     }
 }
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
avatar image
1

Answer by LuisDeliz · Nov 25, 2012 at 05:28 AM

I'd suggest doing a check to stop movement after it reaches its location. That way you only move when you need to move.

Something along the lines of:

 if (target.transform.position != player.transform.position){
 Move();
 }
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

13 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

Related Questions

How do I hurt enemies by jumping on them without getting killed? 1 Answer

enemy attack the player 0 Answers

I use this script, but the enemy lose health if i don´t target him. 1 Answer

I want to attack me enemy and decrease their health, but t won't work, what am I doing wrong with my script? 4 Answers

Detect if player is in range? 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