如何解决统一我如何将速度修改为相对于与世界轴相反的某个方向
我正在编写3D第三人称游戏。我几乎已经完全掌握了播放器的控件,但是唯一不希望的是运动。 此刻运动的方式是,如果我倾斜模拟摇杆或WASD,则我将相对于世界轴沿该方向运动。这不是我想要的,因为当我绕着角色旋转电影摄影机时,角色仍相对于世界轴移动,这意味着我可能从我的角度向后看,但角色仍沿负Z轴移动 我完全知道我想发生的事情,只是我不知道如何在C#中实现它:
- 我想获取活动相机的朝前方向(通常看起来像(1、0,-1)或使用cam.transform.forward打印时看起来像这样)
- 我想获得应该对角色实施的原始速度
- 我想修改此速度,以便零/正向值是相机面对的方式,并将移动速度的方向添加到该方向以获得角色应该移动的方式
如果我根本没有任何意义,那么这是一个正在发生的事的例子:
- 我的角色正对着X轴正向,而相机直接位于他的正后方。我想发生的是,如果我打对了,他会朝负Z方向走,因为那是从相机的直觉角度出发,即从相机所面对的位置开始。相反,发生的事情是角色不断朝着正X前进,因为相对于世界的正Z轴,正X是正确的……也可能没有任何意义,但是如果您正在努力将其可视化的话
这是到目前为止的相关代码:
//SpeedMod is a floating point value that changes the speed the character is moving
//rb is the character' rigidbody
//Movement smothing is a floating point value that adjusts how much the character leans into its veLocity
targetVeLocity = new Vector3(
Input.GetAxis("Horizontal") * speedMod * Time.fixedDeltaTime,rb.veLocity.y,Input.GetAxis("Vertical") * speedMod * Time.fixedDeltaTime);
rb.veLocity = Vector3.Lerp(rb.veLocity,targetVeLocity,movementSmoothing);
//This bit sorts out the rotation of the character,so isnt related to veLocity
if (rb.veLocity.magnitude > 0.001f)
{
targetRotation = Quaternion.LookRotation(new Vector3(Input.GetAxis("Horizontal"),Input.GetAxis("Vertical")),Vector3.up);
transform.rotation =
Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0
?
transform.rotation
:
Quaternion.Lerp(
transform.rotation,targetRotation,rotationSpeed * Time.fixedDeltaTime);
}
这都是固定的upate函数 感谢您阅读所有内容。我真的很喜欢这方面的帮助,因为我努力奋斗了一个好星期
谢谢!
解决方法
使用transform
。它已经为您提供了指示。
例如:
transform.up;
transform.right;
transform.forward;
如果您需要任意方向,则:
var inWorldSpace = transform.TransformDirection( objectSpaceVector );
var inObjectSpace = transform.InverseTransformDirection( worldSpaceVector);
,
对于那些感兴趣的人,我最终要做的是将lookrotation与cam.forward和cam.up方向结合使用,然后将其乘以我计算出的相对于相机方向的速度。现在,我有一个刺客信条式相机,向前移动时会卡在播放器后面,但是当我静止不动时让我自由旋转相机!
if (isGrounded)
{
//Handle the actual movement & rotation
targetVelocity = Quaternion.LookRotation(cam.transform.forward,cam.transform.up) * new Vector3(
Input.GetAxis("Horizontal") * speedMod,rb.velocity.y,Input.GetAxis("Vertical") * speedMod);
rb.velocity = Vector3.Lerp(rb.velocity,targetVelocity,movementSmoothing);
}
if (rb.velocity.magnitude > 0.001f)
{
targetRotation = Quaternion.LookRotation(targetVelocity.normalized,Vector3.up);
transform.rotation = new Quaternion(
transform.rotation.x,Quaternion.Lerp(
transform.rotation,targetRotation,rotationSpeed).y,transform.rotation.z,transform.rotation.w);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。