Unity 3D-限制相机旋转 [英] Unity 3D - Limit Camera Rotation

查看:473
本文介绍了Unity 3D-限制相机旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了这个问题的几个遮篷,并且我都尝试过这些遮篷,但是它们要么损坏了我的相机,要么总体上不起作用.

I have found several awnsers to this question online, and I have tried all of them, but they either break my camera, or just overall don't work.

这是我的剧本:

using UnityEngine;
using System.Collections;

public class fp : MonoBehaviour
{

public float speedH = 2.0f;
public float speedV = 2.0f;

private float yaw = 0.0f;
private float pitch = 0.0f;

void Update()
{
    yaw += speedH * Input.GetAxis("Mouse X");
    pitch -= speedV * Input.GetAxis("Mouse Y");

    transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
}
}

据我所知,有3种解决方案,但是我不知道如何实现任何解决方案

As far as I know, there is 3 solutions to this problem, but I don't know how to implement any of the solutions

解决方案1:将上面的脚本转换为Unityscript(我对C#的了解很少),并且可以使用"if"语句解决问题.

Solution 1: Convert the script above to Unityscript (I have little expirience with C#) and I can solve the problem with "if" statements.

解决方案2:提供C#代码以将脚本上的角度限制为所有轴成90度角

Solution 2: Provide the C# code to limit the angle on my script to an angle of 90 degrees all axis

解决方案3:以上所有

推荐答案

没有尝试限制代码中的任何轴.使用临时变量通过每次tome Input.GetAxis更改将其递增来限制轴.如果达到最小值或最大值,则要将其限制为Mathf.Clamp,以将其限制在最小值和最大值/角度之间.

There is no attempt to limit any axis in your code. Use a temporary variable to limit your axis by incrementing it each tome Input.GetAxis changes. If it reaches the min or max value you want to limit it to then the Mathf.Clamp to clamp it between that min and max values/angle.

修改了,以将FPS摄像头限制在两个轴上,而不是通常的y轴限制.

Modified this to limit your FPS camera in both axis instead of usual y-axis limit.

public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;

//Y limit
public float yMaxLimit = 45.0f;
public float yMinLimit = -45.0f;
float yRotCounter = 0.0f;

//X limit
public float xMaxLimit = 45.0f;
public float xMinLimit = -45.0f;
float xRotCounter = 0.0f;

Transform player;

void Start()
{
    player = Camera.main.transform;
}

// Update is called once per frame
void Update()
{
    //Get X value and limit it
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    xRotCounter = Mathf.Clamp(xRotCounter, xMinLimit, xMaxLimit);

    //Get Y value and limit it
    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);
}

这篇关于Unity 3D-限制相机旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆