Reputation: 11
I want double jump but not much idea to do! managed single jump by far. Followed some youtube tutorials and some articles however none of them worked for me I know I am doing wrong because I am not familiar with c# .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walk_script : MonoBehaviour
{
public float speed = 4;
public float gravity = 8;
public float jumpSpeed = 5.0f;
Vector3 moveDirection = Vector3.zero;
CharacterController controller;
Animator anim;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.W))
{
anim.SetBool("running", true);
moveDirection = new Vector3(0, 0, 1);
moveDirection *= speed;
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetBool("running", false);
moveDirection = new Vector3(0, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("jump", true);
moveDirection.y = jumpSpeed;
}
else
{
anim.SetBool("jump", false);
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Upvotes: 1
Views: 231
Reputation: 67
You can checkout this answer for a proper jump and double jump implementation but here is your code with double jump.
You need to manage hasJumped boolean to check if you can jump again while in the air. Set it to true when jumped while on the ground and check if it's true so you can jump again only once while in the air.
bool hasJumped = false;
// Update is called once per frame
void Update()
{
if (controller.isGrounded)
{
if (Input.GetKey(KeyCode.W))
{
anim.SetBool("running", true);
moveDirection = new Vector3(0, 0, 1);
moveDirection *= speed;
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetBool("running", false);
moveDirection = new Vector3(0, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("jump", true);
hasJumped = true;
moveDirection.y = jumpSpeed;
}
else
{
anim.SetBool("jump", false);
}
}
else
{
if (hasJumped && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Second Jump");
anim.SetBool("jump", true);
hasJumped = false;
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
Upvotes: 2