user5090788
user5090788

Reputation:

Restricting an object's rotation angle

So my friend an I tried to make a canon that in unity 3d with rectangles and circle. We want to restrict the angle of rotation of the canon to be more than -90 degre and less than 0 degree. Here is the codes:

But when playing the game, the canon rotates more than minus ninety degree and fall off the ground.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;




public class PlayerController : MonoBehaviour
{
    private float rotation = 0f;
    public GameObject wheele;
    private float xMin = -1.0f, xMax = 1.0f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (rotation >= -90)
                transform.parent.transform.Rotate(new Vector3(0.0f, 0.0f, rotation));

            rotation -= 8;
            //Mathf.Clamp(rotation, -90.0f, 0);
        }
        if(Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (rotation >= -90)
                transform.parent.transform.RotateAround(wheele.transform.position, Vector3.up,20);

            rotation += 2;
            Mathf.Clamp(rotation, -90.0f, 0);
        }


    }
}

As you can see in the following image:

enter image description here

Upvotes: 0

Views: 91

Answers (1)

Phillip
Phillip

Reputation: 660

From https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

Returns
float The float result between the min and max values.

Thus, you need to set rotation to the return value of the Mathf.Clamp function, as Clamp does not actually do anything to the passed in value parameter. This is called a Pure function.

Change:

Mathf.Clamp(rotation, -90.0f, 0);

To:

rotation = Mathf.Clamp(rotation, -90.0f, 0);

Upvotes: 3

Related Questions