Reputation: 21
I copied this code from a Youtube Unity tutorial video and I can't figure out what's wrong with it.
When I play the game in unity and I try to look up with my mouse it tries to stop me from doing so.
using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour {
public float movementSpeed = 5.0f;
float verticalRotation = 0;
public float upDownRange = 60.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Rotation
float rotLeftRight = Input.GetAxis("Mouse X");
transform.Rotate(0, rotLeftRight, 0);
verticalRotation = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
//Movement
float forwardSpeed = Input.GetAxis ("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
Vector3 speed = new Vector3 (sideSpeed, 0, forwardSpeed);
speed = transform.rotation * speed;
CharacterController cc = GetComponent<CharacterController>();
cc.SimpleMove (speed);
}
}
Upvotes: 2
Views: 408
Reputation: 671
If this script is on the camera itself then:
Here, try replacing your update with something a little simpler.
void Update()
{
//Rotation
float rotLeftRight = Input.GetAxis("Mouse X");
//transform.Rotate(0, rotLeftRight, 0);
verticalRotation = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
//Only add the rotation when both values are set so you don't overwrite the first one.
transform.Rotate(-verticalRotation, rotLeftRight, 0);
//Movement
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
Vector3 speed = new Vector3(sideSpeed, 0, forwardSpeed);
speed = transform.rotation * speed;
CharacterController cc = GetComponent<CharacterController>();
cc.SimpleMove(speed);
}
I believe your main problem was that you were setting Y to 0 when setting the X and then a little after you would set the X to 0 by setting the Y and since this is in the update, it was looking jittery and ending up with both at 0.
Upvotes: 1
Reputation: 103
I think the problem is that you assign the Mouse Y value in verticalRotation instead of increment it.
Try something like:
float yAxis = Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation + yAxis, -upDownRange, upDownRange);`
Maybe you should also have a rotationSpeed like you have movementSpeed.
Upvotes: 1