# How can I raycast between two moving objects in Unity?

How can I raycast between two moving objects?

I want to raycast from a moving enemy to a moving player. I dont know how to actually code to make the direction work.

using UnityEngine;
using System.Collections;

public class Enemy_Manage_Two : MonoBehaviour {

public GameObject player;

// Use this for initialization
void Start () { }

// Update is called once per frame
void Update () {

player = GameObject.FindGameObjectWithTag ("Player");
//Debug.Log (player.transform.position + " " + transform.position);

Ray ray = new Ray (transform.position, player.transform.position);
RaycastHit hit;

Debug.DrawRay (transform.position, player.transform.position,
Color.red);

if(Physics.Raycast(ray, out hit)) {
gameObject.renderer.material.color = Color.blue;
} else {
gameObject.renderer.material.color = Color.white;
}
}
}


http://docs.unity3d.com/ScriptReference/Ray.html

This shows us that ray takes 2 parameters; an origin( the place the ray is being cast from ), and a direction. This is where your code is wrong, you pass in the enemy position for an origin, and pass in the player's position for the direction.

A direction should be a normalised vector. To get the direction from one point to another, you must subtract the origin position from the target position and then normalise. So, your code would end up like this:

Vector3 direction = ( player.transform.position - transform.position ).normalized;
Ray     ray       = new Ray( transform.position, direction );


We get the vector difference between the player and the enemy( the vector between the player and enemy ), then we normalise so the vector is of unity length and only describes a direction. Using that and an origin, Ray can figure out that it must shoot from origin towards direction.

• I tried this code. And i made it when player is touched with the raycast. The enemy will turn blue. And white when its not. But for some reason it doesnt stay blue when its touched with the raycast. Dec 17, 2014 at 10:45
• The normalisation doesn't work. the direction is still fixed. it doesnt chage raycast when i move the player. Feb 23, 2015 at 18:38
• @JekasG can you tell me if the object stays blue for a short period of time and then immediately goes back to white? Feb 24, 2015 at 2:24

Subtract to get the position difference:

/**
*  Show ray between two points
*/
void ShowRayBetweenPoints (Vector3 p1, Vector3 p2)
{
Debug.DrawRay (p1, (p2 - p1), Color.yellow);
}