【发布时间】:2021-09-09 11:28:43
【问题描述】:
你好,我在零重力下有像宇航员一样的角色控制,但我想在 y 轴上局部旋转它,但它不能旋转。我尝试在 y 轴上旋转它,但玩家正在相对于世界旋转。我想要它相对于对象。谢谢你的帮助。
这是我的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Astronaut : MonoBehaviour
{
private static AstronautControls astronautControls;
public Rigidbody rb;
public float force;
public float torque;
public Vector2 move;
float rotateHorizontal;
float rotateVertical;
float upDown;
public PlayerInput playerInput;
private void Awake()
{
astronautControls = new AstronautControls();
}
private void OnEnable()
{
astronautControls.Enable();
}
private void OnDisable()
{
astronautControls.Disable();
}
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Move();
MoveUpDown();
RotateHorizontal();
RotateVertical();
}
private void Move()
{
move = playerInput.actions["Move"].ReadValue<Vector2>();
rb.AddForce(transform.forward * force * move.y * Time.deltaTime);
rb.AddForce(transform.right * force * move.x * Time.deltaTime);
rb.AddForce(transform.up * force * upDown * Time.deltaTime);
}
private void MoveUpDown()
{
upDown = playerInput.actions["MoveVertical"].ReadValue<float>();
rb.AddForce(transform.up * force * upDown * Time.deltaTime);
}
private void RotateHorizontal()
{
rotateHorizontal = playerInput.actions["RotateHorizontal"].ReadValue<float>();
MouseLook.Z += rotateHorizontal;
}
//here is the problem when i rotate it seems it has gimbal lock or something i want local rotate relative to the player
private void RotateVertical()
{
rotateVertical = playerInput.actions["RotateVertical"].ReadValue<float>();
MouseLook.Y += rotateVertical;
}
}
这是鼠标的样子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class MouseLook : MonoBehaviour
{
Mouse mouse;
public static float X;
public static float Y;
public static float Z;
const float MIN_X = -90f;
const float MAX_X = 90f;
const float MIN_Y = -180f;
const float MAX_Y = 180f;
public static Vector3 euler;
public float Sensitivity;
void Awake()
{
mouse = Mouse.current;
euler = transform.rotation.eulerAngles;
X = euler.x;
Y = euler.y;
Z = euler.z;
}
void Update()
{
X -= mouse.delta.y.ReadValue() * (Sensitivity * Time.deltaTime);
if (X < MIN_X) X = MIN_X;
else if (X > MAX_X) X = MAX_X;
Y += mouse.delta.x.ReadValue() * (Sensitivity * Time.deltaTime);
if (Y < MIN_Y) Y = MIN_Y;
else if (Y > MAX_Y) Y = MAX_Y;
transform.parent.localRotation = Quaternion.Euler(X, Y, Z);
}
}
我的刚体设置
【问题讨论】:
-
你能不能不使用
RotateAround之类的东西并传入父母的本地transform.Up作为第二个参数?transform.RotateAround(transform.position, parent.transform.up, speed * Time.deltaTime);。其他选项是使用transform.Rotate(0, yRotation, 0, Space.Self);,因为Space.Self应该会在其本地空间中旋转对象,而不是在世界空间中。 -
因为它不适合我的上一条评论,所以你可以采取的最后一种方法是将原始角度乘以更改后的角度
transform.rotation = originAngle * Quaternion.Euler(xRotationChange, yRotationChange, zRotationChange);。