首页 > 解决方案 > 头部不会随身体旋转

问题描述

我制作了一个脚本,根据 x 轴上的 x 位置更改玩家方向。但我想做一些事情,以便角色可以根据鼠标上的 y 位置上下查看。我试图实现它,但它似乎不起作用,我不知道为什么。

这是我的脚本:

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

public class CharacterMovement : MonoBehaviour
{
    CharacterController characterController;


    private float xaxis = 0.0f;
    private float yaxis = 0.0f;
    public float horizontalMovementSpeed = 2f;
    public float verticalMovementSpeed = 2f;

    public float xSensitivity = 2f;
    public float ySensitivity = 2f;

    public Transform neck;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update ()
    {
        if(!characterController.isGrounded)
        {
            transform.Translate(Input.GetAxis("Horizontal") * horizontalMovementSpeed * Time.deltaTime, 0f, Input.GetAxis("Vertical") * verticalMovementSpeed * Time.deltaTime);
            xaxis += Input.GetAxis("Mouse X") * xSensitivity;
            yaxis += Input.GetAxis("Mouse Y") * ySensitivity;
            transform.eulerAngles = new Vector2(0, xaxis);

            yaxis = Mathf.Clamp(yaxis, -40, 85);
            neck.eulerAngles = new Vector2(yaxis, 0);
        }
    }
}

标签: c#unity3d

解决方案


我假设您正在制作 2D 游戏,因为您的代码使用 Vector2s。

您可以更改您的实现以使用 transform.LookAt 方法,并通过鼠标位置。

https://docs.unity3d.com/ScriptReference/Transform.LookAt.html


推荐阅读