Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
1.5 kB
3
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    //the controllerrrrr
    public CharacterController controller;
    //character speed 
    public float speed = 12f;

    //gravity-related
    public float gravity = -9.81f;

    //ground check code set up
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    bool isGrounded;

    //jump height
    public float jumpHeight = 3f;

    //gravity-related
    Vector3 velocity;

    // Update is called once per frame
    void Update()
    {
        //small sphere created
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        //getting the input
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        //making sure movement working well
        Vector3 move = transform.right * x + transform.forward * z;
        controller.Move(move * speed * Time.deltaTime);

        //jump physics
        if (Input.GetButtonDown("Jump") && isGrounded) {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        //gravityyyy
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}
Leave a Comment