gpt4 book ai didi

object - 使用 Mathf.Clamp() 限制对象旋转时出现问题

转载 作者:行者123 更新时间:2023-12-03 01:09:34 24 4
gpt4 key购买 nike

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

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

最佳答案

您发布的代码会限制 z 位置。你想要的是使用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);
}

关于object - 使用 Mathf.Clamp() 限制对象旋转时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com