Why do I only have left/right mouse movement
Keep in mind that only been looking into coding this past week and I'm not sure on how to make everything work for a simple first PersonController/Camera
I've been reading on how to create the code and I am the closest I've been on making it work using this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class FPController : MonoBehaviour {
public float speed = 5f;
private Transform cam;
private Rigidbody rb;
private Vector3 velocity = Vector3.zero;
private float mouseSensitivity = 250f;
private float verticalLookRotation;
//use this for initialization
void Start ()
{
rb = GetComponent<Rigidbody>();
cam = Camera.main.transform;
}
//update is called once per frame
void Update ()
{
float xMov = Input.GetAxisRaw("Horizontal");
float yMov = Input.GetAxisRaw("Vertical");
float zMov = Input.GetAxisRaw("Jump");
Vector3 movHor = transform.right * xMov; // (1, 0, 0,)
Vector3 movVer = transform.forward * yMov; // (0, 0, 1,)
Vector3 movUp = transform.up * zMov; // (0, 1, 0,)
velocity = (movHor + movVer + movUp).normalized * speed;
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * Time.deltaTime * mouseSensitivity);
verticalLookRotation += Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSensitivity;
verticalLookRotation = Mathf.Clamp(verticalLookRotation,-60, 60);
cam.localEulerAngles = Vector3.left * verticalLookRotation;
}
private void FixedUpdate()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
}
After following The video on Coding First Person Controller
After following along and Checking over the code multiple times I see this in my console
If anyone that knows a bit more about this than I do could explain what I did wrong and how to fix it would make me very grateful! Thank you in advance!
Ive just noticed looking back at the code is that i dont have a horizontal axis rotation and may be the cause of me no being able to look up
Answer by vinilly · May 15, 2018 at 03:50 PM
The error is null reference - meaning camera.main.transform.(missing reference here);
Just some examples to set reference - Example;
cam = camera.main.transform.position;
cam = camera.main.transform.up;
cam = camera.main.transform.left;
cam = camera.main.transform.translate;
cam = camera.main.transform.lookat;
cam = camera.main.transform.right;
cam = camera.main.transform.eulerangles;
cam = camera.main.transform.rotation;
cam = camera.main.transform.forward;