使 3D Object 看起来像面对 2D space 中的一个点

Make a 3D Object look like it is facing a point in an 2D space

您首先会注意到的是复杂而混乱的标题。 那么让我解释一下。

我正在尝试使用 Unity 在 3D space 中制作 2D 游戏。我正在使用 3D 角色作为播放器。看起来像这样:

如您所见,背景(Google 地图)是二维的。虽然玩家是一个 3D Object 躺在地上(它看起来就像是站立的)。

到目前为止一切正常。但我希望 3D 角色看起来像面对背景贴图上的点击点。

例如:

还有两个例子:

黑色圆圈代表点击的位置。所以我完全不知道是否有办法做到这一点,或者即使有可能做到这一点。

我尝试了以下代码,但它只会让我的角色在不同的轴上旋转:

    Vector3 targetDir = tapped.position - transform.position;

    float step = speed * Time.deltaTime;

    Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);

    transform.rotation = Quaternion.LookRotation(newDir);

有没有办法做到这一点?我目前没有想法...... 如果能得到任何帮助,我将非常高兴!

这应该可以解决问题。使你的模型成为一个 child 未旋转的空洞,面向就像你的第一张图片,并在其上放置下面的脚本。我不知道你是怎么看的,这是我在统一中尝试过的。希望对你有帮助。

using UnityEngine;

public class LookAtTarget : MonoBehaviour {

    //assign in inspector
    public Collider floor;

    //make sure you Camera is taged as MainCamera, or make it public and assign in inspector
    Camera mainCamera;

    RaycastHit rayHit;

    //not needed when assigned in the inspector    
    void Start() {
        mainCamera = Camera.main;
    }

    void Update () {

        if(Input.GetMouseButtonUp(0)) {

            if(floor.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), out rayHit, Mathf.Infinity)) {
                //its actually the inverse of the lookDirection, but thats is because the rotation around z later.
                Vector3 lookDirection = transform.position - rayHit.point;

                float angle = Vector3.Angle(lookDirection, transform.forward);

                transform.rotation = Quaternion.AngleAxis(Vector3.Dot(Vector3.right, lookDirection) > 0 ? angle : angle * -1, Vector3.forward);

            } 

        }

    }
}