Question by
cruiselick · Jan 21 at 01:46 PM ·
movementfpsfpscontroller
Restrict Movement Changing Mid-air With CharacterController
Hi! I am making a FPS style game, and I am making the movement. I want the player to be able to use the mouse to look in the direction they want to move (only on the ground). But in the air, all movement should be restricted, and their velocity should be the velocity they had coming into the jump. Camera movement should still work, but not affect the player object. See code below.
MouseLook.cs (on main camera which is a child of the Player object with the charactercontroller)
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// 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");
float mouseY = Input.GetAxis("Mouse Y");
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
PlayerMovement.cs (on the Player object with the charactercontroller)
using System;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
CharacterController controller;
[SerializeField] float speed = 12f;
[SerializeField] Transform groundCheck;
[SerializeField] float groundDistance = 0.4f;
[SerializeField] LayerMask groundMask;
[SerializeField] float gravity;
[SerializeField] float jumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private 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 = new Vector3();
move = transform.right * x + transform.forward * z;
if (Input.GetButtonDown("Jump") && isGrounded)
{
jump();
}
//freefall physics require time ^2
velocity.y += gravity * Time.deltaTime;
controller.Move(move * speed * Time.deltaTime);
controller.Move(velocity * Time.deltaTime);
}
private void jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613051936im_/https://answers.unity.com/themes/thub/images/avi.jpg)