Hello, I am new in 3D Unity so I was watching tutorial on youtube but I have an issue with moving script
This is code for looking around with mouse
using UnityEngine;
public class Eyes : MonoBehaviour
{
public float mouseSensitivity = 250f;
public Transform playerBody;
public float xRotation;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
This is code for movement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public CharacterController Player;
public float speed = 12f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float gravity = -9.81f;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float z = Input.GetAxis("Vertical");
float x = Input.GetAxis("Horizontal");
Vector3 move = transform.right * x + transform.forward * z;
Player.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
Player.Move(velocity * Time.deltaTime);
}
}
Problem is that whenever I look up and start walking, player start going forward but also up and then velocity brings it back on the ground.
I think roundabout could be placing Box collider on top of the player, let it move with it but fix y position but when I think about it, there could also be problem with stairs and so on, so I hope there is some way to fix it in code.
Thank you for any advice