- Home /
Question by
Master_Shadman · Dec 26, 2021 at 06:34 AM ·
jumpingfirst-person-controller
I am trying to make a first person controller but I can't make ta player jump. Can I solve this problem without importing assets?
//Here is how my code looks like
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ControlScript : MonoBehaviour { [SerializeField] Transform firstPersonCamera = null;
bool isSprinting => canSprint && Input.GetKey(sprintKey);
[Header("Functional Variables")]
[SerializeField] private bool lockCursor = true;
[SerializeField] private bool canSprint = true;
[Header("Control Variables")]
[SerializeField] private KeyCode sprintKey = KeyCode.LeftShift;
[Header("Movement Variables")]
[SerializeField] private float mouseSensitivity = 3.5f;
[SerializeField] private float movementSpeed = 6.0f;
[SerializeField] private float sprintSpeed = 10.0f;
[Header("Smoothing Variables")]
[SerializeField] private float moveSmoothTime = 0.3f;
[SerializeField] private float mouseSmoothTime = 0.03f;
[Header("Jumping Variables")]
[SerializeField] private float gravity = 13.0f;
float upwardForce = 0.0f;
float cameraPitch = 0.0f;
CharacterController controller = null;
Vector2 currentMoveInput = Vector2.zero;
Vector2 currentMoveInputVelocity = Vector2.zero;
Vector2 currentMouseInput = Vector2.zero;
Vector2 currentMouseInputVelocity = Vector2.zero;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
void Update()
{
UpdateMouseLook();
UpdateMovement();
}
void UpdateMouseLook()
{
Vector2 mouseInput = new Vector2 (Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")) * mouseSensitivity;
currentMouseInput = Vector2.SmoothDamp(currentMouseInput, mouseInput, ref currentMouseInputVelocity, mouseSmoothTime);
cameraPitch -= currentMouseInput.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -90f, 90f);
firstPersonCamera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * mouseInput.x * mouseSensitivity);
}
void UpdateMovement()
{
Vector2 moveInput = new Vector2 ( Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveInput.Normalize();
currentMoveInput = Vector2.SmoothDamp(currentMoveInput, moveInput, ref currentMoveInputVelocity, moveSmoothTime);
if (controller.isGrounded)
{
upwardForce = 0f;
}
upwardForce -= gravity * Time.deltaTime;
Vector3 move = (transform.forward * currentMoveInput.y + transform.right * currentMoveInput.x) * (isSprinting ? sprintSpeed : movementSpeed) + Vector3.up * upwardForce;
controller.Move(move * Time.deltaTime);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613050937im_/https://answers.unity.com/themes/thub/images/avi.jpg)