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 /
avatar image
0
Question by Saravia95 · May 21, 2014 at 10:56 PM · raycastdetectionpathartificial intelligence

Raycast on an AI Game object

I need to make a raycast from an enemy game object to detect how close it is to a terrain wall to be able to turn around and find another path, I have tried on my own already but I did not get good results. I was hoping someone would be able to help me make a script that can do this properly and be intergrated into my enemies AI code. Thank you!

Here is the enemies' AI code: using UnityEngine; using System.Collections;

 [RequireComponent(typeof(CharacterController))]
 public class AIScript : MonoBehaviour
 {
 
 
 
     
     
     Transform _player;
 
     Transform _Raptor;
     [SerializeField]
     public float
         _moveSpeed = 5.0f;
     /*[SerializeField]
         float
                 Distance = 0.0f;*/
     [SerializeField]
     public float
         _gravity = 2.0f;
     public float _yVelocity = 0.0f;
 
 
     // Cached variables
     CharacterController _controller;
     protected Animator RaptorAnimator;
     Transform _transform;
     
     ChangeDirection _ChangeDirection;
         //Movement variables;
 
     float speed = 5f;
     float gravity = 100f;
     Vector3 moveDirection;
     Vector3 _target;
     float maxRotSpeed = 200.0f;
     float minTime = 0.1f;
     float _velocity;
     bool change;
     float range;
     bool chase = false;
     int RandomAnimation = 1;
     int OldRandomAnimation = 0;
 
 
 
     RaycastHit hit;
     
     void Start()
     {
         _controller = GetComponent<CharacterController>();
         _transform = GetComponent<Transform>();
 
 
         RaptorAnimator = GetComponent<Animator> ();
         GameObject playerGameObject = GameObject.FindGameObjectWithTag ("Player");
         _player = playerGameObject.transform;
 
 
         GameObject EnemyGameObject = GameObject.FindGameObjectWithTag ("Raptor");
         _Raptor = EnemyGameObject.transform;
 
         _ChangeDirection = GetComponentInChildren<ChangeDirection> ();
         range = 2f;
         _target = GetTarget();
         InvokeRepeating("NewTarget", 0.01f, 2.0f);
     }
 
 
 
     void OnTriggerStay (Collider inrange)
     {
 
 
         if (inrange.tag == "WallorTree") {
             Debug.Log ("Touching");
             
             //wallhit = true;
         } else {
             //wallhit = false;
         }
 
         if (inrange.tag == "Player"&& _controller.isGrounded==false) 
         {
             //Debug.Log ("Not Touching");
             RaptorAnimator.SetBool ("RunDistance", true);
             _moveSpeed = 25;
             chase = true;
         }
 
 
 
     
     }
     void OnTriggerExit(Collider outofrange)
     {
         if (outofrange.tag == "Player"&& _controller.isGrounded==false) 
         {
             RaptorAnimator.SetBool ("RunDistance", false);
             _moveSpeed = 5;
             chase = false;
         }
     }
     
     void Update()
     {
 
     
 
         if (_ChangeDirection.wallhit != false) {    
 
 
                         //NewTarget ();
 
                         //if(hit.distance==100){
                         //print("There is something in front of the object!");
                         //}
             Debug.Log("IM HITTING A WALL");
             _Raptor.transform.Rotate (0,180,0);
             //_ChangeDirection.wallhit = false;
         } else {
 
 
         //    _ChangeDirection.wallhit = true;
         }
 
         if(chase == false){
             if (change) _target = GetTarget();
             
             if (Vector3.Distance(_transform.position, _target) > range )
             {
                 Move();
                 RaptorAnimator.SetBool ("Idle", false);
 
             }else{
                 RaptorAnimator.SetBool ("Idle", true);
                 RandomAnimation =     Random.Range(0, 10);
             //    RaptorAnimator.SetBool ("Animation Running", true);
 
                 if(RandomAnimation != OldRandomAnimation){
                 RaptorAnimator.SetInteger ("RandomAnimationIdle", RandomAnimation);
                 }else{
                 RandomAnimation =     Random.Range(0, 10);
                 }
             }
                 
 
             
             
             
 
 
         }else{
             RaptorAnimator.SetBool ("Idle", false);
             Vector3 direction = _player.position - transform.position;
             
             direction.Normalize ();
             
             Vector3 velocity = direction * _moveSpeed;
             
             
             
             
             if (!_controller.isGrounded) {
                 _yVelocity -= _gravity;
             }
             
             velocity.y = _yVelocity;
             direction.y = 0;
             transform.rotation = Quaternion.LookRotation (direction);
             _controller.Move (velocity * Time.deltaTime);
 
         }
 
     }
     
     void Move()
     {
         // Movement
         moveDirection = _transform.forward;
         moveDirection *= speed;
         moveDirection.y -= gravity * Time.deltaTime;
         _controller.Move(moveDirection * Time.deltaTime);
         //Rotation
         var newRotation = Quaternion.LookRotation(_target - _transform.position).eulerAngles;
         var angles = _transform.rotation.eulerAngles;
         _transform.rotation = Quaternion.Euler(angles.x,
                                                Mathf.SmoothDampAngle(angles.y, newRotation.y, ref _velocity, minTime, maxRotSpeed),
                                                angles.z);
     }
     
     Vector3 GetTarget()
     {
         return new Vector3(Random.Range(0, 300), 0, Random.Range(0, 300));
     }
     
     void NewTarget()
     {
         int choice = Random.Range(0, 3);
         switch (choice)
         {
         case 0:
             change = true;
             break;
         case 1:
             change = false;
             break;
         case 2:
             _target = transform.position;
             break;
         }
     }
 }
 
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

1 Reply

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

Answer by PippyLongbeard · May 22, 2014 at 12:51 AM

'Physics.Raycast' can be used for this.

 Physics.Raycast(_Raptor.position, _Raptor.transform.forward, rayDistance);

This would return true if the raycast hits something. 'rayDistance' would be how close the raptor is going to be before it notices the wall. You'll have to play around with that. However, this would detect anything in front of the raptor. To detect only the wall, you can use a RaycastHit.

 RaycastHit hit;
 
 if(Physics.Raycast(_Raptor.position, _Raptor.transform.forward, rayDistance, out hit))
 {
     if(hit.transform.name=="Wall")
     {
         //Do whatever
     }
 }

That's an example on how you'd do that. You don't necessarily need to search for the name. It can be a tag, property, etc. Hope this helps!

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 Saravia95 · May 22, 2014 at 02:01 AM 0
Share

Yeah this helps loads! thanks so much!

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 RayCast a triangular field of view for my autonomous moving agent 4 Answers

How to Check for Enemie in Front? Raycast is not Enough! 2 Answers

enemy Raycast cone detection 0 Answers

Slant Physics Raycast Implementation 0 Answers

Detect obstacle on path 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