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 /
avatar image
0
Question by Paul2357 · Aug 30, 2016 at 03:13 PM · c#raycastraycastingdetectionattack

Raycast causes all enemies to attack

So for my game, I have tried a few different ways of detecting my player to get the enemies to stop and attack. However, I want only the current one that detects the player to stop and proceed to attack (they are all prefabs of the same model).

I've tried using a raycast to project a ray both forwards and backwards from the enemy for detection. This seems to work, but all of the enemies in the scene stop and proceed to do the attack animation (and they get stuck doing this and won't return to their patrol state once the player isn't detected anymore).

I believe one problem with it getting stuck is destroying the enemy before the player leaves the detection zone. Outside of that I am stumped as to how I should go about fixing this is.

Enemy Attack:

  void Update()
     {
         #region Commented Out
         //Debug.Log(playerSeen);
 
         //Vector3 relativePos = target.position - transform.position;
         //Quaternion rotation = Quaternion.LookRotation(relativePos);
         //rotation.y = 0;
         //rotation.x = 0;
         //rotation.z = 0;
 
         //transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * fireSpeed);
         #endregion
 
         ////Grabs the forward vector of this game object
         Vector3 fwd = this.transform.TransformDirection(Vector3.forward);
         Debug.DrawRay(transform.position + (transform.up * -0.2f), -fwd * 3, Color.green);
         Debug.DrawRay(transform.position + (transform.up * -0.2f), fwd * 3, Color.red);
 
         //Raycast to detect player
         if (Physics.Raycast(transform.position + (transform.up * -0.2f), fwd * 3, out hit, 3) && this.hit.collider.gameObject == playerLoc ||
             Physics.Raycast(transform.position + (transform.up * -0.2f), -fwd * 3, out hit, 3) && this.hit.collider.gameObject == playerLoc)
         {
             playerSeen = true;
             //Debug.Log("HIT");
             Debug.Log("This should be true: " + playerSeen);
         }
         else
         {
             playerSeen = false;
             Debug.Log("This should be false: " + playerSeen);
         }
 
         Debug.Log(playerSeen);
 
         //Get distance between player and the enemy
         distance = Vector3.Distance(transform.position, target.position);
 
         if (distance < range && Time.time > lastShotTime + (3.0f / fireRate) && playerSeen)
         {
                 lastShotTime = Time.time;
                 LaunchProjectile();
         }
     }

Enemy Movement:

 void Update()
     {
         //Moves if the player isn't seen and stops/attacks if the player is seen
         if (!playerSeen)
         {
             //Start Movement
             StartCoroutine(Movement());
             
             //Animation
             anim.SetBool("Patrolling", true);
         }
         else
         {
             //Animation
             anim.SetBool("Patrolling", false);
             
             //Stop Movement
             StopCoroutine(Movement());
 
             //Handles flipping enemy to face the target while playerSeen
             if (enemyAttack.target.position.x < this.transform.position.x)
             {
                 this.transform.rotation = lookLeft;
             }
             else if (enemyAttack.target.position.x > this.transform.position.x)
             {
                 this.transform.rotation = lookRight;
             }
         }
     }
 
  IEnumerator Movement()
     {
         //Check for position and switch direction flag if condition is met
         if (transform.position == targetLoc.position)
         {
             switchDirection = true;
         }
 
         if (transform.position == startLoc.position)
         {
             switchDirection = false;
         }
 
         //Handles movement between two points
         if (switchDirection)
         {
             //Flip Model to face other direction
             transform.rotation = lookLeft;
 
             //Move the model
             transform.position = Vector3.MoveTowards(transform.position, startLoc.position, moveSpeed);
         }
         else if (!switchDirection)
         {
             //Flip Model to face other direction
             transform.rotation = lookRight;
 
             //Move the model
             transform.position = Vector3.MoveTowards(transform.position, targetLoc.position, moveSpeed);
         }
 
         //Tells the compiler that there is no return...error handling
         yield return null;
     }
Comment
Add comment · Show 11
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 Paul2357 · Aug 30, 2016 at 03:15 PM 0
Share

@ScaniX Wondering if you maybe would be able to help me out with this one too

avatar image juicyz · Aug 30, 2016 at 04:44 PM 0
Share

How and where is playerSeen defined? Both scripts, one script? What is its definition?

avatar image Paul2357 juicyz · Aug 30, 2016 at 04:57 PM 0
Share

@juicyz playerSeen is defined in the Enemy parent class.

it is defined as

     //Player Seen
     public static bool playerSeen = false;
avatar image ScaniX Paul2357 · Aug 30, 2016 at 05:37 PM 2
Share

As I feared: It is static. Which means: All instances share the same bool value. You should remove the static modifier.

Show more comments
Show more comments
avatar image ScaniX · Aug 30, 2016 at 05:00 PM 0
Share

On first glance I don't see a reason why all of them should stop. Possible causes would be: playerSeen is a static member, all of them share the same anim instance. What is the exact state? Do all the script instances enter the "else" from the if in Update()?

One remark: Your coroutine is none. Coroutines are used to do things that have a longer duration in parallel to the normal processing. You are just doing a single step and return. You also normally don't start them each frame. The thing you are doing can be just moved to the Update(). In your case I don't think you need a coroutine at all.

avatar image Paul2357 ScaniX · Sep 02, 2016 at 12:18 PM 0
Share

@ScaniX I have a question about this. So I removed the static modifier and it seems to work alright.

However, now my children don't seem to see the correct value of the boolean and it remains false. I had to switch to a trigger zone to get the code to let the enemies stop and attack. I'm pretty sure I have it inheriting correctly.

avatar image ScaniX Paul2357 · Sep 02, 2016 at 01:18 PM 0
Share

How old are your children? ;)

I don't really understand your problem. "See the correct value"? The bool should have the correct value: true if the player is seen and false immediately when he vanishes from sight (raycast). If you want access to that value, you should get a reference to that script (preferably not each Update(), but in the Start() or via inspector) and just access the public member. Public members are normally shown in inspector and serialized, so you might want to add [NonSerialized] to it or make it private and add a getter method.

Show more comments

1 Reply

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

Answer by Cynikal · Aug 30, 2016 at 05:49 PM

Remove the static modifier.

Also, you could be using: Time.deltaTime to make it framerate independent.

Comment
Add comment · Show 3 · 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 Paul2357 · Sep 01, 2016 at 08:42 PM 0
Share

@Cynikal

To be honest I don't remember using the static modifier -_-

Also could you elaborate more on using Time.deltaTime to make is framerate independent? Would that be a passed parameter to the raycast declaration itself?

avatar image NerdClown Paul2357 · Sep 02, 2016 at 12:42 PM 1
Share

If you move something forward by a certain distance per frame (by moving it in Update which is called once per frame), it will move twice as fast on a system where you get 100 frame per second than it would on a system giving 50 FPS. To get around that stuff, you can use Time.deltaTime.

It's simply the amount of time passes since the last frame. So if you want something to move 10 meters per second you can do it like this (taken from the official docs):

 using UnityEngine;
 using System.Collections;
 
 public class ExampleClass : $$anonymous$$onoBehaviour {
     void Update() {
         float translation = Time.deltaTime * 10;
         transform.Translate(0, 0, translation);
     }
 }

This way, if 0.1 second has passed since last call to Update, it'll be moved forward 1 meter. If an entire second has passed (because of some nasty lag or whatever), it'll move it the entire ten meters, making sure you'll get a speed of 10m/s independent of frame rate.

avatar image Paul2357 NerdClown · Sep 02, 2016 at 12:44 PM 1
Share

@NerdClown

Thanks for the explanation. I saw the Unity docs thing but I didn't totally understand what they had meant. I appreciate it!

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 to check if an empty GameObject is inside an object? 2 Answers

Raycast/Melee Attack Help Please! 1 Answer

Raycast function doesn't work. 1 Answer

ray cast not working ? 2 Answers

Raycast From Within An Object 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