首页 > 解决方案 > 如何根据方向将相机定位在玩家后面并在Unity中查看该方向

问题描述

我正在使用自动相机创建游戏。我希望这台相机能够显示玩家正在朝哪里移动。该游戏让玩家拥有广泛的运动范围,而不仅仅是在 3D 中四处走动。因此,例如,如果玩家朝地面坠落,则摄像机应将自身定位在玩家上方,俯视玩家和地面。如果玩家向前移动,相机应该将自己定位在玩家身后,向前看。

我已经包含了我认为是我在下面尝试过的所有内容的最佳实现,并附有解释功能和我的一些问题的评论。

///This should position the camera in a straight line between the player and the direction the player is heading. This seems to work to work nearly as expected, but seems to line up to what I believe to be the opposite direction in some cases.
v3T = player.transform.position - (player.GetComponent<Rigidbody().velocity - player.transform.position);
p2 = player.transform.position + v3T.normalized * 7.0f;
finalP = Vector3.SmoothDamp(finalP,p2,ref velocity, 0.002f, 850f);
transform.position = new Vector3(finalP.x, finalP.y, finalP.z);

//Using a LookAt like this leads for decent results, but not perfect. Possibly due to me not lining up the camera correctly?
transform.LookAt(player.transform.position);

//Using a Lookat in direction the player is moving doesn't give me the expected result. It seems to lose track of the player easily, and doesn't go in the direction that I thought it would at all times.
//transform.LookAt(player.GetComponent<Rigidbody>().velocity)

相机无法正常工作

相机正常工作

标签: unity3dcamera

解决方案


Ok, so I think I've kinda wrapped my head around this. There seems to be a clipping/intersection issue between the camera and the player which results in weird behaviour from the camera. I set up a small project, imported the 3rd person Standard Unity Controller and copied your code to the camera. At first I encountered the issue where the camera shows the player from the side. So then I added a static vector to the camera's starting position to correct the camera from overlapping with the Third Person Character and it fixed the issue (for me and my setup at least). Here is the Update function of the Camera component.

    ///This should position the camera in a straight line between the player and the direction the player is heading. This seems to work to work nearly as expected, but seems to line up to what I believe to be the opposite direction in some cases.
    v3T = player.transform.position + new Vector3(5,5,5); //- (player.GetComponent<Rigidbody>().velocity - player.transform.position);
    p2 = player.transform.position + v3T.normalized * 7.0f;
    finalP = Vector3.SmoothDamp(finalP,p2,ref velocity, 0.002f, 850f);
    transform.position = new Vector3(finalP.x, finalP.y, finalP.z);

    //Using a LookAt like this leads for decent results, but not perfect. Possibly due to me not lining up the camera correctly?
    transform.LookAt(player.transform.position);

    //Using a Lookat in direction the player is moving doesn't give me the expected result. It seems to lose track of the player easily, and doesn't go in the direction that I thought it would at all times.
    //transform.LookAt(player.GetComponent<Rigidbody>().velocity)

Here are some screenshots I took of my setup and of the camera's behaviour.


推荐阅读