been trying to fix this for a while,
and i need help
code is here : |
/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
public bool jump = false;
float horizontalMove = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
}
void FixedUpdate()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, false, jump);
jump = false;
}
}
You need to test if the player is touching the ground before you jump. There are many tutorials on youtube for this.
For Example.
(14) A Perfect Jump in Unity - A Complete Guide - YouTube
You may need to look at a few of them to see if it meets your needs.
In my library there is a full script including jump or double jumps and movement.
https://www.rp-interactive.nl/library.html
It’s all about giving it a variable that checks if the object has something under it to jump from (platform,ground) Only then a jump should work.
add a bool called isOnGround;
public bool isOnGround = true; // unless your player starts in midair then exclude the "= true" part
then implement it in an if statement where the user presses spacebar AND the player is on the ground, then the player can jump,
if (Input.GetKeyDown(KeyCode.Space) && isOnGround) //&& !gameOver
{
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
}
(also add an playerRb component)
private Rigidbody playerRb;
playerRb = GetComponent<Rigidbody>();
then make it that if the player touches the ground it is allowed to jump again
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Ground"))
{
isOnGround = true;
}
You can add any if statements like that and name the tag whatever you want also
if(collision.gameObject.CompareTag("Platform"))
{
isOnGround = true;
}
}
Also notice how the 1st ex. is missing a curly bracket and how the 2nd ex. has an extra one. BOTH of those if statements are in the “private void OnCollisionEnter(Collision collision)” (That part in red is important or the code wont work)
Hopefully this helps