2014-09-13 13 views
3

z 축에서 객체를 회전시키는 게임을하고 있습니다. 총 회전 수를 80 도로 제한해야합니다. 다음 코드를 시도했지만 작동하지 않습니다. minAngle = -40.0f 및 maxAngle = 40.0fMathf.Clamp()로 객체 회전 제한 문제들

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

답변

7

게시 한 코드는 z 위치를 고정시킵니다. 당신이 원하는 것은 여기 Imapler으로 좋은 솔루션의 정적 버전 대신 각도 자체를 변경하는 것을입니다 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); 
} 
+0

이 방법에 감사드립니다. 그것은 내 문제를 거의 해결했다! 유일한 것은 회전이 -50 또는 50을지나도록 허용 된 경우 회전이 멈추어 마우스 움직임에 응답하지 않는 것입니다. 나는이 한계를 지켰 음을 확인했고 그것은 훌륭하게 작동합니다! 도와 주셔서 감사합니다. – jadkins4

+0

GENIUS! 이 질문에 대한 웹 주위에는 많은 답변이 있지만이 솔루션을 제외한 모든 솔루션은 작동하지 않습니다. 훌륭한! –

1

을 사용하는 것입니다, 그것은 campled 각도를 반환, 그래서 그것은 어떤 사용할 수 있습니다 중심선.

public static float ClampAngle(
    float currentValue, 
    float minAngle, 
    float maxAngle, 
    float clampAroundAngle = 0 
) { 
    return Mathf.Clamp(
     WrapAngle(currentValue - (clampAroundAngle + 180)) - 180, 
     minAngle, 
     maxAngle 
    ) + 360 + clampAroundAngle; 
} 

public static float WrapAngle(float angle) 
{ 
    while (angle < 0) { 
     angle += 360; 
    } 
    return Mathf.Repeat(angle, 360); 
} 

또는 당신이 WrapAngle 방법을 사용할 것으로 예상하지 않는 경우, 여기 올인원 버전 : 그래서 지금

public static float ClampAngle(
    float currentValue, 
    float minAngle, 
    float maxAngle, 
    float clampAroundAngle = 0 
) { 
    float angle = currentValue - (clampAroundAngle + 180); 

    while (angle < 0) { 
     angle += 360; 
    } 

    angle = Mathf.Repeat(angle, 360); 

    return Mathf.Clamp(
     angle - 180, 
     minAngle, 
     maxAngle 
    ) + 360 + clampAroundAngle; 
} 

당신은 할 수 있습니다 :

transform.localEulerAngles.x = YourMathf.ClampAngle(
    transform.localEulerAngles.x, 
    minX, 
    maxX 
);