为第三人称射击游戏的光线投射

时间:2015-04-23 22:17:51

标签: c# unity3d

我需要从我的玩家角色到我的相机光线投射的热门对象进行光线投射,但我无法让我的代码工作,它似乎总是偏移。

        void Update () {

    RaycastHit hit;
    Ray playerAim = playerCamera.GetComponent < Camera > ().ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2 ));
    Physics.Raycast(playerAim, out hit);
    Debug.DrawRay(playerAim.origin, playerAim.direction * hit.distance, Color.green);

    if (Physics.Raycast(playerAim, out hit)){
        // something was hit
        RaycastHit playerHit;
        Physics.Raycast(transform.position, hit.transform.position,  out playerHit);
        Debug.DrawRay(transform.position, playerHit.transform.position, Color.red);

        Debug.Log ("Distance from camera: "+ hit.distance);
        Debug.Log ("Distance from player: "+ playerHit.distance);
    }
}

http://i.stack.imgur.com/HzdVU.jpg

我认为Debug.DrawRay(transform.position, playerHit.transform.position, Color.red);应该从我的玩家画到一条红线到相机击中点的绿线末端,而不是它射到地板上。

1 个答案:

答案 0 :(得分:3)

将Debug.DrawRay更改为Debug.DrawLine!

Debug.DrawRay需要Vector3作为原点,Vector3作为方向,而不是第二个“目标”位置。

这是我的解决方案!

enter image description here

void FixedUpdate() {

    RaycastHit cameraHit;
    Ray cameraAim = playerCamera.GetComponent < Camera > ().ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2 ));
    Physics.Raycast(cameraAim, out cameraHit, 100f);
    Debug.DrawLine(cameraAim.origin, cameraHit.point, Color.green);
    Vector3 cameraHitPoint = cameraHit.point;
    float cameraDistance = cameraHit.distance;

    if (Physics.Raycast(cameraAim, out cameraHit)){
        // something was hit
        RaycastHit playerHit;
        Physics.Raycast(transform.position + new Vector3 (0f, 1.8f, 0f), cameraHitPoint-transform.position - new Vector3 (0f, 1.8f, 0f), out playerHit, 100f);
        Debug.DrawRay(transform.position + new Vector3 (0f, 1.8f, 0f), cameraHitPoint-transform.position - new Vector3 (0f, 1.8f, 0f), Color.red);

        float playerDistance = playerHit.distance;
        Debug.Log ("Distance from player: "+ playerDistance);
        Debug.Log ("Distance from camera: "+ cameraDistance);
    }

}