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 HollaKoala · Mar 06, 2013 at 08:47 PM · raycastaimoving

AI Avoiding Obstacles Problem

Hello! I have a working AI script that takes waypoints and if a player gets nearby it will chase the player. However I wanted it to avoid obstacles when doing those two functions. I followed an AI avoiding script using raycasts but I couldn't get it to work with my code. I'm just not sure how I would modify the character move to use the raycast script information.

Here is my AI Script

 var waypoint : Transform[]; // The amount of Waypoint you want
 var patrolSpeed : float = 3;       // The walking speed between Waypoints
 var loop : boolean = true;       // Do you want to keep repeating the Waypoints
 var player : Transform;          // Referance to the Player
 var dampingLook = 6.0;          // How slowly to turn
 var pauseDuration : float = 0;   // How long to pause at a Waypoint
 var attackRange = 10;          // Range to start the attack
 var attackSpeed = 5.0;          // Speed to attack
 var attackLook = 10.0;          // How fast to turn when attacking
 var ASpeed = 1;
 
 private var distanceToPlayer : int; // Distance from the enemy to the Player
 private var currentTime : float;
 private var currentWaypoint : int = 0;
 private var character : CharacterController;
 private var gravity : float = 2.0;
 private var attacking : boolean = false;
 private var isattacking : boolean = false;
 private var captured : boolean = false;
 
     function Awake(){
 
     }
     
     function Start(){
         character = GetComponent(CharacterController);
         animation["bite"].speed = ASpeed;
         animation["bite"].layer = 1;
     }
     
     function Update(){
         // Gets the distance between the enemy and the Player    
         distanceToPlayer = Vector3.Distance(player.position, transform.position);
         if(captured){
              animation["Death"].wrapMode = WrapMode.ClampForever;
              animation.Play("Death");
            }
         else if(distanceToPlayer < attackRange){
            attacking = true;
            attack();
            }else{
            attacking = false;
            }
             if(currentWaypoint < waypoint.length && !attacking && !captured){
                patrol();
                }else{    
                 if(loop && !attacking){
                    currentWaypoint=0;
                 } 
             }
     }
     function patrol(){
         var target : Vector3 = waypoint[currentWaypoint].position;
         target.y = transform.position.y; // This keeps the waypoint at character's height
         var moveDirection : Vector3 = target - transform.position;
         if(moveDirection.magnitude < 0.5){
            if (currentTime == 0) {
              currentTime = Time.time; // Pause over the Waypoint
              animation.Play("idle");
            }
            if ((Time.time - currentTime) >= pauseDuration){
              currentWaypoint++;
              currentTime = 0;
            }
         }else{        
             // This gets the location of the waypoint and rotates the AI to look at the waypoint and dampen the rotation
            var rotation = Quaternion.LookRotation(target - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * dampingLook);
            moveDirection.y = 0;
            moveDirection.y -= gravity; //Gravity so the the AI  stays on the ground
            character.Move(moveDirection.normalized * patrolSpeed * Time.deltaTime);
            animation.Play("trot");
         }  
     }
  
     function attack(){
         // Attack the Player
         if (distanceToPlayer <= 2) {
             animation.Play("bite");
             //var ph: PlayerHealth = gameObject.GetComponent("PlayerHealth");
             //var ph : PlayerHealth = (PlayerHealth)target.GetComponent("PlayerHealth");
             //ph.AdjustCurrentHealth(-10);
         } else {
         animation.Stop("bite");
         // Rotate to face the Player
         var lookPos = player.position - transform.position;
             lookPos.y = 0;
         var rotation = Quaternion.LookRotation(lookPos);
             transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * attackLook);
         // Move towards the Player
         var target : Vector3 = player.position;
         var moveDirection : Vector3 = target - transform.position;
         moveDirection.y = 0; // This helps stop the AI running up off the floor to match the Players Y axis
         moveDirection.y -= gravity; //Gravity so the the AI always stays on the ground
         character.Move(moveDirection.normalized * attackSpeed * Time.deltaTime);
         animation.Play("run");
         }
     }
     
     function OnCollisionEnter(collision : Collision){
         if(collision.gameObject.tag == "Projectile"){
             captured = true;
         }
     }

Here is the AI Raycast Avoiding Script

 function Update () {
 //The directional Vector to our target
 var dir = (target.position - transform.position).normalized;
 var hit : RaycastHit;
 //check for forward raycast
 if(Physics.Raycast(transform.position, transform.forward, hit, 20)) {
     if(hit.transform != transform) {
         dir += hit.normal * 20;
     }
 }
 var leftR = transform.position;
 var rightR = transform.position;
 
 leftR.x -=2;
 rightR.x +=2;
 
 if(Physics.Raycast(leftR, transform.forward, hit, 20)) {
     if(hit.transform != transform) {
         dir += hit.normal * 20;
     }
 }
 
 if(Physics.Raycast(rightR, transform.forward, hit, 20)) {
     if(hit.transform != transform) {
         dir += hit.normal * 20;
     }
 }
 
 var rot = Quaternion.LookRotation(dir);
 
 transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime);
 transform.position += transform.forward * 20 * Time.deltaTime;
 
 }
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 Dr_GeoFry · Jun 07, 2013 at 08:35 PM 0
Share

@Holla$$anonymous$$oala I have a question for you. were you ever able to make the enemy walk between the waypoints? I can only get the enemy to walk to one waypoint. He won't walk to the next waypoint. Any advice

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by darthbator · Jun 07, 2013 at 10:43 PM

Have you looked at Unity Steer yet? That's a good steering package for obstacle avoidance. While doing that during steering is nice (and IMO is good to have even with the method I am about the describe). IMO it's most ideal to rasterize objects into your pathfinding system rather then using a steering agent to move around them. That way the characters plot a path around the obstacles and steer down that path rather then picking a path that might go directly through obstacles and just relying on steering to get you around them.

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

12 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

Related Questions

Visible GameObjects for AI 0 Answers

AI Raycast problem 1 Answer

Fire projectile, tracing a Raycast, enemy AI, 2D 1 Answer

RayCast2D not returning values as expected 0 Answers

AI raycasting problem 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