Unity - 游戏对象看鼠标

Jor*_*nie 5 c# unity-game-engine unityscript

我遇到了问题。

我现在拥有的基本设置有两个对象:我的相机和我的播放器对象。

玩家通过 WASD 上的变换移动,并且应该随着鼠标移动而旋转。

摄像机自上而下(以轻微的“3ps”风格角度,使玩家对象保持在摄像机视角的中心,并根据玩家的旋转进行旋转。

这是玩家移动脚本:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour 
{
    public int playerSpeed = 8;  //players movement speed

    void Update () {
        if (Input.GetKey ("w")) 
        {
            transform.Translate (Vector3.forward * Time.deltaTime * playerSpeed); //move forward
        }  
        if (Input.GetKey ("s")) 
        {
            transform.Translate (Vector3.back * Time.deltaTime * playerSpeed); //move backwards
        }  
        if (Input.GetKey ("a")) 
        {
            transform.Translate (Vector3.left * Time.deltaTime * playerSpeed); //move left
        }  
        if (Input.GetKey ("d")) 
        {
            transform.Translate (Vector3.right * Time.deltaTime * playerSpeed); //move right
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是球员轮换脚本:

using UnityEngine;
using System.Collections;

public class mouseLook : MonoBehaviour {
    private Vector3 inputRotation;
    private Vector3 mousePlacement;
    private Vector3 screenCentre;

    void Update () {
        FindCrap();
        transform.rotation = Quaternion.LookRotation(inputRotation);
    }

    void FindCrap () {
        screenCentre = new Vector3(Screen.width * 0.5f,0,Screen.height * 0.5f);
        mousePlacement = Input.mousePosition;
        mousePlacement.z = mousePlacement.y;
        mousePlacement.y = 0;
        inputRotation = mousePlacement - screenCentre;
    } 
}
Run Code Online (Sandbox Code Playgroud)

我所展示的一切的结果是它旋转,但它不会旋转到鼠标实际所在的位置。

当我用鼠标画圆圈时,它会完全旋转,但不会始终指向鼠标所在的位置。我不知道为什么。

期望的结果是让摄像机(玩家对象的子对象)跟随玩家的移动和旋转,而玩家随着其移动脚本移动,并旋转以指向鼠标所在的位置。

有人有任何想法吗?提前致谢。

编辑:如果有帮助,当前的旋转是这样工作的。

用鼠标在玩家周围绘制大圆圈比在玩家周围绘制非常紧密的圆圈更慢。

Agu*_*987 5

我不确定我是否明白你在做什么。如果你正在尝试做一些类似于游戏“死亡国家”的事情,那么我会建议这样的:

MouseLook.cs

void Update()
{
    Vector3 mouse = Input.mousePosition;
    Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3(
                                                        mouse.x, 
                                                        mouse.y,
                                                        player.transform.position.y));
    Vector3 forward = mouseWorld - player.transform.position;
    player.transform.rotation = Quaternion.LookRotation(forward, Vector3.up);
}
Run Code Online (Sandbox Code Playgroud)

如果你想让相机随着玩家移动和旋转,那么只需让相机成为玩家对象的子对象。