FPS camera with y-axis limit to certain angle

前端 未结 1 1949
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 01:46

I am starting a new game and right now my player can view 360* but I want to limit how far the player looks up in the sky and down (straight up and down). Here\'s my code

相关标签:
1条回答
  • 2020-12-02 02:09

    You have to use Mathf.Clamp to do this. Below is what I use to rotate the camera up/down and left/right. You can modify the yMaxLimit and yMinLimit variables to the angles you want to limit it to. There should be no limit while moving in the x direction.

    public float xMoveThreshold = 1000.0f;
    public float yMoveThreshold = 1000.0f;
    
    public float yMaxLimit = 45.0f;
    public float yMinLimit = -45.0f;
    
    
    float yRotCounter = 0.0f;
    float xRotCounter = 0.0f;
    
    Transform player;
    
    void Start()
    {
        player = Camera.main.transform;
    }
    
    // Update is called once per frame
    void Update()
    {
        xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
        yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
        yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
        //xRotCounter = xRotCounter % 360;//Optional
        player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
    }
    
    0 讨论(0)
提交回复
热议问题