【问题标题】:Add velocity to an object relative to its local axis相对于其局部轴将速度添加到对象
【发布时间】:2020-12-19 22:16:19
【问题描述】:

所以我正在努力实现如何为 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);
         }
     }
 }

如果有人知道如何解决此问题,请添加说明。谢谢!

【问题讨论】:

  • 一般来说你不应该像这样旋转你的对象。 1) 不要动态更改eulerAngles 2) 不要将刚体的操作与变换混合。而是使用例如Rigidbody.MoveRotation 在固定更新中

标签: c# unity3d rigid-bodies


【解决方案1】:

使用transform.TransformDirection将方向从局部空间转换到世界空间:

rb.velocity = transform.TransformDirection(
        new Vector3(xMovement, rb.velocity.y, zMovement));

【讨论】:

  • 但是这对于Y 组件来说不是不正确的,因为它已经在世界空间中了吗? ;)
  • @derHugo 在很多情况下是的,但是如果我们可以确定本地 y 与全局 y 方向相同,我们可以稍微作弊 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2019-09-24
相关资源
最近更新 更多