JekasG
JekasG

Reputation: 145

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;
        }
    }
}

Upvotes: 2

Views: 2353

Answers (1)

roxik0
roxik0

Reputation: 97

Currently I haven't Unity so treat my answer as proof of concept.

//1. You have to calculate vector between enemy and player:
Vector3 direction=player.transform.position - transform.position;
direction.Normalize(); //Normalize vector
//2. Now you can create Ray
Ray ray=new Ray(transform.position,direction);

Upvotes: 1

Related Questions