Question by
RiotRews · Jun 14, 2017 at 05:47 PM ·
mathf.clamp
Hey! I have problem with my FPS controller, where Mathf.Clamp doesn't work. Any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
public float speed = 2f;
public float sensitivity = 5f;
public GameObject cam;
float camRaw;
float camSide;
// Use this for initialization
void Start()
{
// Locks cursor on startup
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
// Movement
float translation = Input.GetAxis("Horizontal") * speed;
float strafe = Input.GetAxis("Vertical") * speed;
// This part smoothes the movement
translation *= Time.deltaTime;
strafe *= Time.deltaTime;
// Translates movement Axis
transform.Translate(translation, 0, strafe);
// (Un)Locks Cursor
if (Input.GetKeyDown("escape"))
Cursor.lockState = CursorLockMode.None;
// Defines camera movement
camRaw -= Input.GetAxis("Mouse Y") * sensitivity;
camSide = Input.GetAxis("Mouse X") * sensitivity;
// Transforms rotation of camera and player
cam.transform.localRotation = Quaternion.Euler(camRaw, 0, 0);
transform.Rotate(0, camSide, 0);
Mathf.Clamp(camRaw, -60f, 60f);
}
}
Comment
Answer by RiotRews · Jun 15, 2017 at 10:06 AM
Nevermind, got clamp fixed and working! For others who are looking for solution, why Clamp suddenly doesn't work, you can use if statements used like shown:
// Clamp
if (camRaw >= 60f)
camRaw = 60f;
if (camRaw <= -60f)
camRaw = -60f;
or, in syntax:
if (Camera y-axis float name >= max float value)
camera y-axis float name = max float value;
if (camera y axis float name <= min float value)
camera y-axis float name = min float value;