玩家是父对象的子对象,并且玩家有自己的子对象一个相机。 当旋转的 Z 为 50 并且 X 和 Y 为 0 时,播放器启动。
然后我使用带有动画的 Player Animator Controller 将 Z 仅从 50 更改为 0。 当游戏开始时,玩家的 Z 轴从 50 变为 0。
播放器附加了一些组件,我尝试在游戏运行时将每个组件一一删除,但没有任何改变/帮助。
玩家已附加一个刚体和一个 Controller 脚本。
玩家相机已附加一个玩家相机 Controller 脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCameraController : MonoBehaviour
{
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
private UnityEngine.GameObject player;
private Vector2 mouseLook;
private Vector2 smoothV;
// Use this for initialization
void Start()
{
player = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
if (PauseManager.gamePaused == false)
{
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
player.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, Vector3.up);
}
}
}
我可以使用鼠标将相机旋转 360 度。 仅当使用鼠标时,它才会更改玩家在 Y 轴上的旋转。
但后来我尝试在游戏运行时为 X、Y 和 Z 上的玩家旋转设置新值,但没有任何变化。
由于某种原因,它正在改变旋转,我看到播放器随动画器或鼠标旋转,但当我更改播放器旋转值时,什么也没有发生。
我还尝试附加一个简单的脚本进行测试,但按下 L 按钮时没有任何变化:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
private void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
var player = GameObject.Find("Player");
player.transform.Rotate(Vector3.left, 25);
}
}
}
我不知道如何旋转播放器,为什么我不能自己旋转它,但我可以使用鼠标 Controller 脚本或动画师旋转它?
最佳答案
您的PlayerCameraController
脚本正在基于mouseLook
字段覆盖旋转。它根本不考虑玩家或相机的当前旋转,因此它只是覆盖任何更改。
不要使用 mouseLook
字段,而是修改相机的 localEulerAngles
并在播放器的 transform
上使用 Rotate
。
public class PlayerCameraController : MonoBehaviour
{
public float sensitivity = 5.0f;
public float smoothing = 2.0f;
private UnityEngine.GameObject player;
private Vector2 smoothV;
// Use this for initialization
void Start()
{
player = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update()
{
if (PauseManager.gamePaused == false)
{
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
md = sensitivity * smoothing * md;
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
Vector3 modifiedEulers = transform.localEulerAngles + Vector3.left * smoothV.y;
// transform euler angles from [0,360) to [-180,180) before clamp
modifiedEulers.x = Mathf.Repeat(modifiedEulers.x + 180f, 360f) - 180f;
modifiedEulers.x = Mathf.Clamp(modifiedEulers.x, -90f, 90f);
transform.localEulerAngles = modifiedEulers;
player.transform.Rotate(0f, smoothV.x, 0f);
}
}
}
关于c# - 为什么我无法旋转播放器变换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59329649/