Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

c# - FPS camera with y-axis limit to certain angle

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

Vector2 mouseLook;
Vector2 smoothV;

public float sensitivity = 5.0f;
public float smoothing = 2.0f;

GameObject player;

void Start () {
    player = this.transform.parent.gameObject;
}

// Update is called once per frame
void Update () {
    var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

    md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
    smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
    smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
    mouseLook += smoothV;

    transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
    player.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, player.transform.up);
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...