简体   繁体   English

Unity 为什么在 3d 自上而下的游戏中,玩家无法转向 cursor? (仅 Y 轴)透视相机/LookAt

[英]Unity Why can't the player turn towards the cursor in a 3d top-down game? (only Y-axis)Perspective Camera/LookAt

The game is made in 3D, and this is the main problem for creating the mechanics of directing the player to the cursor, since it works in 2D.游戏是在 3D 中制作的,这是创建将玩家引导至 cursor 的机制的主要问题,因为它在 2D 中工作。

Here is the player code:下面是播放器代码:

void Update(){
   RaycastHit hit;
   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
   if (Physics.Raycast(ray, out hit)){
      Vector3 pointToLook = hit.point;
      transform.LookAt(2 * transform.position - pointToLook);
   }
}

If that I use Camera.main.ScreenPointToRay and transform.LookAt, maybe they are not optimal for this task.如果我使用 Camera.main.ScreenPointToRay 和 transform.LookAt,那么它们可能不是此任务的最佳选择。

Video with an example of the error带有错误示例的视频

I think the main problem is that your pointToLook is below transform.position , as you are raycasting a plane, which is below.我认为主要问题是你的pointToLook低于transform.position ,因为你正在投射一个平面,它在下面。 So when you use lookAt it directs your object a bit downwards.因此,当您使用 lookAt 时,它会将您的lookAt指向下方。

Your vector transform.position - pointToLook will look a bit in the direction of the plane, so what you want is to take a part of this vector, that is in the same plane as your gameobject.你的向量transform.position - pointToLook会看起来有点在平面的方向上,所以你想要的是取这个向量的一部分,即与你的游戏对象在同一平面上。 Your gameobject lies horizontally with transform.up looking exactly at Vector3.Up你的游戏对象水平放置, transform.up正好在Vector3.Up

So let's make a projection.所以让我们做一个投影。

Vector3 projection = Vector3.ProjectOnPlane(transform.position - pointToLook, Vector3.up);

The next thing you want is to align your transform.forward (or maybe right , depends on your orientation) to that projection.您想要的下一件事是将您的transform.forward (或者可能right ,取决于您的方向)与该投影对齐。

transform.forward = projection.normalized

And one more note: don't use Camera.main in Update() , as it uses FindGameObjectWithTag() which is slow.还有一点需要注意:不要在Update()中使用Camera.main ,因为它使用FindGameObjectWithTag()很慢。 Cache reference to camera at Start()Start()缓存对相机的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM