c# - 头部不会随身体旋转
问题描述
我制作了一个脚本,根据 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);
}
}
}
解决方案
我假设您正在制作 2D 游戏,因为您的代码使用 Vector2s。
您可以更改您的实现以使用 transform.LookAt 方法,并通过鼠标位置。
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
推荐阅读
- c# - 使用表达式
> 在另一个表达式中 > - python - 如何使用 Python 内置函数成功处理大量 .txt 文件?
- javascript - 如何在没有可选查询字符串参数的情况下从 URL 获取路径或 slug
- powerbi - 如何在 Dax 中过滤 M2M 表
- react-native - 以下任务之间的循环依赖关系: :app:bundleReleaseJsAndAssets \--- :app:recordFilesBeforeBundleCommandRelease
- progressive-web-apps - 我为 manifest.json 文件提供了正确的参考,但在 Chrome 开发工具中它说没有检测到清单
- c++ - 如何在 Mexfile 中的 matlab(矩阵、单元格)和 c++(向量或自定义类)之间正确转换变量
- r - 将数据框结果保存为适合复制/粘贴到 word 文件的格式
- php - PHP/MySQL 农历
- file - 弹簧 webflux 通量
转换为输入流