- Home /
Path finding using Raycasting inside of Unity(JavaScript)
So I recently was able to get help with a script and got a relatively satisfying result. This script allows me to input coordinates and then the object that it is applied to will seek out these coordinates while avoiding objects. What I need to know how to do is make so that instead of inputting coordinates it will follow a certain gameObject. This is the script along with comments;
// Avoid Obstacle Script // ---------------------
var speed : float = 10.0; var target : Vector3 = Vector3(0, 0, 0); private var dir : Vector3; private var dirFull : Vector3;
// ----
function FixedUpdate() { // -- Obstacle Avoidance Tutorial --
 // the directional vector to the target
 dir = (target - transform.position).normalized;
 var hit : RaycastHit;
 // check for forward raycast
 if (Physics.Raycast(transform.position, transform.forward, hit, 1)) // 20 is raycast distance
 {
    if (hit.transform != this.transform)
    {
      Debug.DrawLine (transform.position, hit.point, Color.white);
      dir += hit.normal * 20; // 20 is force to repel by
    }
 }
 // more raycasts   
 var leftRay = transform.position + Vector3(-1.5, 0, 0);
 var rightRay = transform.position + Vector3(1.5, 0, 0);
 // check for leftRay raycast
 if (Physics.Raycast(leftRay, transform.forward, hit, 1)) // 20 is raycast distance
 {
    if (hit.transform != this.transform)
    {
      Debug.DrawLine (leftRay, hit.point, Color.red);
      dir += hit.normal * 20; // 20 is force to repel by
    }
 }
 // check for rightRay raycast
 if (Physics.Raycast(rightRay, transform.forward, hit, 1)) // 20 is raycast distance
 {
    if (hit.transform != this.transform)
    {
      Debug.DrawLine (rightRay, hit.point, Color.green);
      dir += hit.normal * 20; // 20 is force to repel by
    }
 }
 // --
 // Movement
 // rotation
 var rot = Quaternion.LookRotation (dir);
 //print ("rot : " + rot);
 transform.rotation = Quaternion.Slerp (transform.rotation, rot, Time.deltaTime);
 //position
 transform.position += transform.forward * (2 * Time.deltaTime); // 20 is speed
 }
Just for a little background on my project in case that might help, I am have the player work his way through a maze and I would like the Enemy be able to find him.
Answer by mactinite77 · Jul 27, 2012 at 03:18 AM
It seems like all you have to do is change your target variable to a Transform type and change all references to that variable to something like target.position, that basically just gets the vector of a transform which is a component found on all gameObjects that I know of.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                