0
\$\begingroup\$

I'm making a player-script/FPS in unity where you walk around with WASD and rotate the camera with mouse x/y axis. The "character"/"Player" should be able to rotate with the mouse X axis. (E.g If you look left and press W, you walk in that direction) This is my code. It worked perfectly fine and suddenly didn't work, and I've tried resetting my camera and re-creating everything but still won't work. Here's my code;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FirstPersonController : MonoBehaviour
{   
    //Multipliers for camera and mouse
    public float movementSpeed = 20.0f;
    public float mouseSensitivity = 5.0f;

    // You can't rotate the camera more than 70 degrees up and down, you dont want to break your neck
    float verticalRot = 0;
    public float rangeUD = 70.0f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Rotate around Y axis
        float rotLR = Input.GetAxis("Mouse X") * mouseSensitivity;
        float rotUD = Input.GetAxis("Mouse Y") * -mouseSensitivity;
 //It works until here, I've tried with debug.log
        Camera.main.transform.Rotate(rotUD, 0, 0);
        transform.Rotate(0, rotLR, 0);

        verticalRot -= Input.GetAxis("Mouse Y") * mouseSensitivity;
        verticalRot = Mathf.Clamp(verticalRot, -rangeUD, rangeUD);

        //Here is where I think the problem is:
        Camera.main.transform.localRotation = Quaternion.Euler(verticalRot, 0, 0);

        // importera getAxis
        float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
        float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;

        // Speed has to be modified to follow the character
        Vector3 speed = new Vector3(sideSpeed, 0, forwardSpeed);

        speed = transform.rotation * speed;
        CharacterController cc = GetComponent<CharacterController>();

        cc.SimpleMove(speed);

    }
}

I am also new to Unity and this is a very basic script, i would appreciate all the help!

\$\endgroup\$
  • \$\begingroup\$ Can you walk us through exactly what changed about the behaviour when it went from working "perfectly fine" to "suddenly didn't work"? There are a lot of ways for a script to not work, up to and including setting your computer on fire, and the specific symptoms like observable in-game behaviour, console warnings/errors, etc. can be a big help in narrowing down the root cause. Also: what were you changing around the time that it stopped working? \$\endgroup\$ – DMGregory May 12 '19 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.