- Home /
Question by
Unlucky_ · Apr 07 at 02:07 PM ·
controller
Double jumping
Hey, I'm trying to make my player able to double jump, but i haven't had success. Can someone help me out? Here's my script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(CharacterController))] public class Player : MonoBehaviour { public Camera cam; public Animator anim; public CharacterController controller;
public float movement;
private float movementspeed;
public float InputX;
public float InputZ;
public float Speed;
public Vector3 desiredMoveDirection;
public bool blockRotationPlayer;
public float allowPlayerRotation;
private float verticalVel;
public bool isGrounded;
public float jumpSpeed;
public float gravity;
private Vector3 moveVector;
void Start()
{
anim = this.GetComponent<Animator>();
controller = this.GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
if (Input.GetButton("Jump"))
{
verticalVel = jumpSpeed;
}
anim.SetBool("Jump", false);
}
else
{
anim.SetBool("Jump", true);
verticalVel -= gravity * Time.deltaTime;
}
InputMovement();
moveVector = new Vector3(0, verticalVel, 0);
controller.Move(moveVector);
}
void PlayerMoveAndRotation()
{
var forward = cam.transform.forward;
var right = cam.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
desiredMoveDirection = forward * InputZ + right * InputX;
if (blockRotationPlayer == false)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(desiredMoveDirection), 0.1f);
}
}
void InputMovement()
{
InputX = Input.GetAxisRaw("Horizontal");
InputZ = Input.GetAxisRaw("Vertical");
movementspeed = movement;
controller.Move(desiredMoveDirection * Time.deltaTime * movementspeed);
anim.SetFloat("InputZ", InputZ, 0.0f, Time.deltaTime);
anim.SetFloat("InputX", InputX, 0.0f, Time.deltaTime);
Speed = new Vector2(InputX, InputZ).sqrMagnitude;
if (Speed == 2)
Speed = 1;
if (Speed > allowPlayerRotation)
{
anim.SetFloat("InputMovement", Speed, .1f, Time.deltaTime);
PlayerMoveAndRotation();
}
else
{
anim.SetFloat("InputMovement", Speed, 0.1f, Time.deltaTime);
desiredMoveDirection.x = 0;
desiredMoveDirection.y = 0;
desiredMoveDirection.z = 0;
}
}
}
Comment
Answer by rh_galaxy · Apr 07 at 07:00 PM
Ok, I don't know if you are happy with the normal jumping, but I assume so.
Then double jumping can be done with something like this (untested):
private int numJump = 0;
void Update()
{
if (Input.GetButton("Jump") && numJump<2)
{
verticalVel = jumpSpeed;
numJump++;
}
if (controller.isGrounded)
{
anim.SetBool("Jump", false);
numJump = 0;
}
else
{
anim.SetBool("Jump", true);
verticalVel -= gravity * Time.deltaTime;
}
InputMovement();
moveVector = new Vector3(0, verticalVel, 0);
controller.Move(moveVector);
}
Your answer