使用 Mathf.Clamp() 限制对象旋转的问题 [英] Problems limiting object rotation with Mathf.Clamp()

查看:24
本文介绍了使用 Mathf.Clamp() 限制对象旋转的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个在 z 轴上旋转对象的游戏.我需要将总旋转限制为 80 度.我尝试了以下代码,但它不起作用.minAngle = -40.0f 和 maxAngle = 40.0f

I am working on a game that rotates an object on the z axis. I need to limit the total rotation to 80 degrees. I tried the following code, but it doesn't work. minAngle = -40.0f and maxAngle = 40.0f

Vector3 pos = transform.position;
pos.z = Mathf.Clamp(pos.z, minAngle, maxAngle);
transform.position = pos;

推荐答案

您发布的代码限制了 z 位置.你想要的是使用transform.rotation

The code you posted clamps the z position. What you want is to use transform.rotation

void ClampRotation(float minAngle, float maxAngle, float clampAroundAngle = 0)
{
    //clampAroundAngle is the angle you want the clamp to originate from
    //For example a value of 90, with a min=-45 and max=45, will let the angle go 45 degrees away from 90

    //Adjust to make 0 be right side up
    clampAroundAngle += 180;

    //Get the angle of the z axis and rotate it up side down
    float z = transform.rotation.eulerAngles.z - clampAroundAngle;

    z = WrapAngle(z);

    //Move range to [-180, 180]
    z -= 180;

    //Clamp to desired range
    z = Mathf.Clamp(z, minAngle, maxAngle);

    //Move range back to [0, 360]
    z += 180;

    //Set the angle back to the transform and rotate it back to right side up
    transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, z + clampAroundAngle);
}

//Make sure angle is within 0,360 range
float WrapAngle(float angle)
{
    //If its negative rotate until its positive
    while (angle < 0)
        angle += 360;

    //If its to positive rotate until within range
    return Mathf.Repeat(angle, 360);
}

这篇关于使用 Mathf.Clamp() 限制对象旋转的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆