使3D对象看起来像是面向2D空间中的点

时间:2017-10-11 18:37:11

标签: c# google-maps unity3d 3d 2d

你会注意到的第一件事是复杂和令人困惑的标题。 所以让我解释一下。

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

Pic1

正如您所见,背景(谷歌地图)是二维的。虽然播放器是放置在地面上的3D物体(它看起来像是站立的)。

到目前为止工作正常。但我希望3D角色看起来像是在背景地图上面对一个点击点。

例如:

Hes looking towards

还有两个例子:

enter image description here

enter image description here

黑色圆圈代表拍子位置。所以我完全不知道如果有办法做到这一点,或者即使它可以做到这一点。

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

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

有没有办法实现这一目标?我目前没有想法...... 我会很高兴能得到任何帮助!

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。让你的模型成为一个未旋转的空的孩子,面对就像在你的第一张图片中,然后将下面的脚本放在上面。我不知道你怎么看待它,这是我在团结中尝试的。希望它有所帮助。

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

            } 

        }

    }
}