1

我正在 Unity 上制作一个自上而下的游戏,所以我使用 x 和 z 轴作为我的平面。我让我的角色旋转 x 90, y 0, z 0 使其平放在平面上。一旦我点击播放,角色就会垂直旋转?!我认为这与我的脚本面对鼠标位置有关。

它应该是什么样子:

在此处输入图像描述

当我点击播放时:

在此处输入图像描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public static float moveSpeed = 10f;

    private Rigidbody rb;

    private Vector3 moveInput;
    private Vector3 moveVelocity;

    // Update is called once per frame

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
    }

    void Update()
    {
        // Setting up movement along x and z axis. (Top Down Shooter)
        moveInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
        moveVelocity = moveInput * moveSpeed;

        //Make character look at mouse.
        var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
        var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
    }

    void FixedUpdate()
    {   
        // Allows character to move.
        rb.velocity = moveVelocity;
    }
}
4

1 回答 1

3

想通了:我正在回答自己的问题以帮助他人。

Vector3 difference = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position); 
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; 
transform.rotation = Quaternion.Euler(90f, 0f, rotZ -90);

这正是我想要的!

于 2019-11-14T06:52:19.127 回答