Crossplayer
Crossplayer

Reputation: 43

i have a problem with player movment while jumping

the only problem that i face that the player only jump when they build momentum and i dont want that i want player jump by pressing space while standing or moving i tried velocity.y=jumphight which doesnt work too

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovment : MonoBehaviour
{ 
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    Vector3 velocity;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    bool isGrounded;
    public float JumpHight = 3f;


    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
        if(isGrounded && velocity.y<0)
        {
            controller.slopeLimit = 45.0f;
            velocity.y = -2f;//when player is grounded it just put some gravity to him all the time
        }
        float x = Input.GetAxis("Horizontal");//moves left and right
        float z = Input.GetAxis("Vertical");//moves up and down
        Vector3 move = transform.right * x + transform.forward * z;
        controller.Move(move*speed*Time.deltaTime);
        if(Input.GetButtonDown("Jump") && controller.isGrounded)
        {


            velocity.y = Mathf.Sqrt(JumpHight * -2f * gravity);
        }
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);




    }
}

Upvotes: 0

Views: 145

Answers (2)

Sbfam 22
Sbfam 22

Reputation: 91

Vector3 velocity;
public float gravity = -9.82f;
public float JumpHeight = 3f;

if(Input.GetButtonDown("Jump")
{
  velocity.y = Matf.Sqrt(JumpHeight * -2f * gravity);
}

You could also do what the other person said, the reason this person's line of code might not have worked it due to how weak it is. Here is an updated version of said code.

GetComponent<Rigidbody>().AddForce(Vector3.up * 10f ,ForceMode.Impulse);

The reason I am using the * is to increase the "up" variable since it means Vector3(0f, 1f, 0f); and using the ForceMode.Impulse to make it more volatile and stronger.

Hope this code helps you in your game making, Kind Regards. SB

Upvotes: 0

Skin_phil
Skin_phil

Reputation: 708

you could use an addforce on the rigidbody with a ForceMode force , and if you don't want your physic depending on the fps use FixedUpdate instead of update

   GetComponent<Rigidbody>().AddForce(Vector3.up,ForceMode.Force);

Upvotes: 1

Related Questions