简体   繁体   中英

I'm trying to make a simple 2d platformer game, but my code wont let me jump

This is the error and I'm using this tutorial

This is my first game in C# and I'm not sure what to do because nobody in the comments said anything about this that I've seen.

This is the exact code that I have wrote.


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

public class PlayerMovement : MonoBehaviour
{
    public float movementSpeed;
    public Rigidbody2D rb;

    public float jumpForce = 20f;
    public Transform feet;
    public LayerMask groundLayers;

    float mx;

    private void Update()
    {
        mx = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            Jump();
        }
    }

    private void FixedUpdate()
    {
        Vector2 movement = new Vector2(mx * movementSpeed, rb.velocity.y);

        rb.velocity = movement;
    }

    void Jump()
    {
        Vector2 movement = new Vector2(rb.velocity.x, jumpForce);

        rb.velocity = movement;
    }

    public bool IsGrounded()
    {
        Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, 0.5f, groundLayers);

        if (groundCheck != null)
        {
            return true;
        }

        return false;
    }
}

Thanks in advance, I'm new to C# and its a big help. :)

For detecting the grounded status of the player i would simply use the OnCollisionEnter() method thet you can implement in your script. It detects when any collider attached to your gameobject touches an other. To tell apart the ground from other objects simply use the following:

if(collision.collider.gameobject.comparetag("ground")
{
//if this is true, set a boolean value to indicate that the player is grounded
//and when the player jumps, always set that boolean to false
}

For this to work you have to set the tag for your floor as "ground" (you have to create that yourself).

To jump, i would rather use rg.AddForce(jumpForce, ForceMode.Impulse) as it's cleaner in my opinion.

Also, as a start i would use Keycode.Space in the GetKeyDown() method instead of "Jump" as it gets rid of a variable that you have to check when debugging.

If it still doesn't work, feel free to write a comment here and let me know.

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