Samuel Alvarez
Samuel Alvarez

Reputation: 1

How do I add the feature to make player jump higher by holding down space?

I'm quite new to coding and making games. I created this script with the help of some YT tutorials and I was wondering how to make my character jump higher while holding doing the space bar. I tried different things but non worked properly. Here's my character code. Thanks!

using System;
using UnityEngine;
using UnityEngine.UI;

public class TPMovementScript : MonoBehaviour
{

    public CharacterController controller;
    public Transform cam;

    public float speed = 6f;
    public float jump = 10f;
    public float gravity = -9.81f;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    public float jumpHeight = 3f;



    Vector3 velocity;
    bool isGrounded;

    public float turnSmoothTime = 0.1f;

    float turnSmoothVelocity;

    // Update is called once per frame
    void Update()
    {
        //Checks if player is grounded & resets velocity
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

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

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);

        //Makes Player move Using WASD or upDownLeftRight
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized.normalized;


        if (isGrounded && Input.GetKey(KeyCode.Space))
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
            
        }

        //Makes Character face direction and makes forward to camera position
        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDir.normalized * speed * Time.deltaTime);

        }

    }
}

Upvotes: 0

Views: 63

Answers (1)

destroyerx512
destroyerx512

Reputation: 11

This looks like answer to your problem https://www.youtube.com/watch?v=j111eKN8sJw and code is similar.

Upvotes: 1

Related Questions