简体   繁体   中英

Unity Jump if touch ground

Upon left clicking, the Player should jump if the condition of colliding with the "Ground" layer is true.

Problem: when I click it is not making the jump.

Hierarchy(3)

  • Main Camera
  • Player
  • Floor

Inspector info: 在此处输入图片说明

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

public class PlayerController : MonoBehaviour
{
    
    public float jumpForce = 25f;
    private Rigidbody2D rigidBody;
    
    void Awake()
    {
        rigidBody = GetComponent<Rigidbody2D>();    
    }
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            Jump();
        }
    }
    
    void Jump(){
    
        if (IsGrounded()) {
            rigidBody.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
        }
    }
        
     
    public LayerMask groundLayer;
    
    bool IsGrounded()
    {
        if (Physics2D.Raycast(this.transform.position, Vector2.down, 0.2f, groundLayer.value)) {
            return true;
        }
        else {
            return false;
        }
    }
        
}

I can't see how big your player is but make sure the raycast can actually reach the floor since it's only 0.2 meters long. You can use Debug.DrawLine() to see the raycast in the editor.

Also make sure the jump force value is high enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM