首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >轴上的统一定向

轴上的统一定向
EN

Stack Overflow用户
提问于 2018-10-25 04:39:59
回答 1查看 502关注 0票数 0

我有一个第一人称刚体胶囊,旋转,这样他将永远垂直于重力方向。我想把我的播放器旋转到一边,这样玩家的相机就不会垂直旋转。

我的代码是,

代码语言:javascript
复制
void Update() {
    FixOrientation();
}

void FixOrientation()
{
    if (trans.up != -GetGravityDirection())
    {
        Quaternion targetRotation = Quaternion.FromToRotation(trans.up, -GetGravityDirection()) * trans.localRotation;
        trans.localRotation = Quaternion.RotateTowards(trans.localRotation, targetRotation, 5f);
    }
}

结果是,

在上面的图片中,我改变了重力方向,指向天花板。

这个代码只在全局x轴上旋转,而不管他面对的是哪里,这意味着当我面对全局正向或向后时,播放机将垂直旋转摄像机。我想让它在侧面旋转(局部z轴)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-25 05:40:27

统一已经有了一种精确的方法:Transform.Rotate有一个过载的角度和一个旋转轴。

可能看上去像

代码语言:javascript
复制
// rotation speed in degrees per second
public float RotationSpeed;

void Update()
{
    FixOrientation();
}

void FixOrientation()
{
    if (transform.up != -GetGravityDirection())
    {
        // Get the current angle between the up axis and your negative gravity vector
        var difference = Vector3.Angle(transform.up, -GetGravityDirection());

        // This simply assures you don't overshoot and rotate more than required 
        // to avoid a back-forward loop
        // also use Time.deltaTime for a frame-independent rotation speed
        var maxStep = Mathf.Min(difference, RotationSpeed * Time.deltaTime);

        // you only want ot rotate around local Z axis
        // Space.Self makes sure you use the local axis
        transform.Rotate(0, 0, maxStep, Space.Self);
        }
    }

一个赛德诺特人:

只是在一般情况下,小心两个向量的直接比较

代码语言:javascript
复制
trans.up != -GetGravityDirection()

使用0.00001的近似。在您的情况下,这应该是好的,无论如何,但为了比较,您应该使用

代码语言:javascript
复制
Vector3.Angle(vector1, vector2) > threshold

定义更宽或更强的阈值

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52981463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档