相对于其局部轴向对象添加速度
Add velocity to an object relative to its local axis
所以我正在努力了解如何为 rb 对象添加相对于其旋转的速度。这是我的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public CinemachineFreeLook camFreeLook;
public float speed = 5f;
private float refVelocity;
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.visible = false;
}
void Update()
{
float xMovement = Input.GetAxis("Horizontal") * speed;
float zMovement = Input.GetAxis("Vertical") * speed;
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
rb.velocity = new Vector3(xMovement, rb.velocity.y, zMovement); // Here is the problem. It moves the player relative to the world axis, but im trying to move it relative to it's local axis
}
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y, camFreeLook.m_XAxis.Value, ref refVelocity, 0.1f);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, rotationY, transform.eulerAngles.z);
}
}
}
如果有人知道如何解决这个问题,请添加说明。谢谢!
使用transform.TransformDirection
将方向从本地space转换为世界space:
rb.velocity = transform.TransformDirection(
new Vector3(xMovement, rb.velocity.y, zMovement));
所以我正在努力了解如何为 rb 对象添加相对于其旋转的速度。这是我的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public CinemachineFreeLook camFreeLook;
public float speed = 5f;
private float refVelocity;
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.visible = false;
}
void Update()
{
float xMovement = Input.GetAxis("Horizontal") * speed;
float zMovement = Input.GetAxis("Vertical") * speed;
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
rb.velocity = new Vector3(xMovement, rb.velocity.y, zMovement); // Here is the problem. It moves the player relative to the world axis, but im trying to move it relative to it's local axis
}
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
float rotationY = Mathf.SmoothDampAngle(transform.eulerAngles.y, camFreeLook.m_XAxis.Value, ref refVelocity, 0.1f);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, rotationY, transform.eulerAngles.z);
}
}
}
如果有人知道如何解决这个问题,请添加说明。谢谢!
使用transform.TransformDirection
将方向从本地space转换为世界space:
rb.velocity = transform.TransformDirection(
new Vector3(xMovement, rb.velocity.y, zMovement));