I am trying to make my own FPS Game in unity but my movement script doesn’t work.
Any suggestions?
MouseMovementScript:
using UnityEngine;
public class MouseMovement : MonoBehaviour
{
public float MouseSensitivity = 100f;
float xRotation = 0f;
float yRotation = 0f;
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);
yRotation -= mouseX;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}
}
PlayerMovementScript:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public float Speed = 12f;
public float Gravity = -9.81f * 2;
public float JumpHeight = 3f;
public Transform GroundCheck;
public float GroundDistance = 0.4f;
public LayerMask GroundMask;
Vector3 Velocity;
bool IsGrounded;
bool IsMoving;
private Vector3 LastPosition = new Vector3(0f, 0f, 0f);
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
IsGrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance, GroundMask);
if (IsGrounded && Velocity.y < 0)
{
Velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * Speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && IsGrounded)
{
Velocity.y = Mathf.Sqrt(JumpHeight * -2f * Gravity);
Velocity.y += Gravity * Time.deltaTime;
controller.Move(Velocity * Time.deltaTime);
if (LastPosition != gameObject.transform.position && IsGrounded == true)
{
IsMoving = true;
}
else
{
IsMoving = false;
}
LastPosition = gameObject.transform.position;
}
}
}
When trying to move i was stuck in the ground.
Do you have a idea how to fix it?
I am thankful for everyone helping me!
Have a nice day!
Huh? I can´t post it like this because it´s “mostly code”?
What should i type here?
Anyways Hope that there is just a small mistake in the code 🙂
New contributor
Crossaint is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.