Search code examples
c#unity-game-enginerotationgame-development

Unity, specific rotation


I have this object that I want to rotate but I want to Clamp the possible rotation to lets say 10 degrees. For example, the rotation around Z happens while the player has the A key pressed down, comes down to 10 as it can-t go any further, and it slowly rotates back to 0 when the key is released... the same happens when u press D but in - (minus) direction ofcourse... The rotations are around a Global axes and only around Z ( with A and D keys) and around X (W and S keys)... Hope I was clear :)

so far my code looks like this:

public float rotationSpeed = 100f;
    public float returnSpeed = 10f;
    private float targetAngle = 0f;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            targetAngle = Mathf.Clamp(targetAngle + rotationSpeed * Time.deltaTime, 0, 10);
        }
        else
        {
            targetAngle = Mathf.LerpAngle(targetAngle, 0, returnSpeed * Time.deltaTime);
        }
        transform.rotation = Quaternion.Euler(0, 0, targetAngle);

    }
}

it works ok but when I add the condition for D it acts badly...


Solution

  • Without overthinking it too much I would say you are on the right track, yo should just not clamp between 0 and 10 but rather between -10 and 10

    public float rotationSpeed = 100f;
    public float returnSpeed = 10f;
    private float targetAngleZ = 0f;
    private float targetAngleX = 0f;
    
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            targetAngleZ += rotationSpeed * Time.deltaTime;
        }
        else if(Input.GetKey(KeyCode.D))
        {
            targetAngleZ -= rotationSpeed * Time.deltaTime;  
        }
        else
        {
            targetAngleZ = Mathf.LerpAngle(targetAngleZ, 0, returnSpeed * Time.deltaTime);
        }
    
        
        if (Input.GetKey(KeyCode.W))
        {
            targetAngleX += rotationSpeed * Time.deltaTime;
        }
        else if(Input.GetKey(KeyCode.S))
        {
            targetAngleX -= rotationSpeed * Time.deltaTime;  
        }
        else
        {
            targetAngleX = Mathf.MoveTowards(targetAngleX, 0, returnSpeed * Time.deltaTime);
        }
    
        targetAngleZ = Mathf.Clamp(targetAngleZ, -10, 10);
        targetAngleX = Mathf.Clamp(targetAngleX, -10, 10);
        
        transform.rotation = Quaternion.Euler(targetAngleX, 0, targetAngleZ);
    }