如何在Unity中的两个移动对象之间进行光线投射?

时间:2014-12-19 13:10:00

标签: c# unity3d raycasting

如何在两个移动物体之间进行光线投射?

我想从一个移动的敌人射线投射到一个移动的玩家。我不知道如何实际编码以使方向有效。

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

1 个答案:

答案 0 :(得分:0)

目前我还没有Unity,所以请将我的答案视为概念验证。

//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);