【问题标题】:I'm trying to make a simple 2d platformer game, but my code wont let me jump我正在尝试制作一个简单的 2d 平台游戏,但我的代码不会让我跳
【发布时间】:2021-11-25 16:45:47
【问题描述】:

这是error 和 我正在使用这个tutorial

这是我在 C# 中的第一个游戏,我不知道该怎么做,因为 cmets 中没有人提及我所见过的任何事情。

这是我写的确切代码。


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;
    }
}

在此先感谢,我是 C# 新手,这对我有很大帮助。 :)

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

    为了检测玩家的接地状态,我只需使用 OnCollisionEnter() 方法,您可以在脚本中实现该方法。它检测连接到您的游戏对象的任何对撞机何时接触到另一个。要将地面与其他物体区分开来,只需使用以下命令:

    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
    }
    

    为此,您必须将地板的标签设置为“地面”(您必须自己创建)。

    要跳转,我宁愿使用rg.AddForce(jumpForce, ForceMode.Impulse),因为我认为它更干净。

    另外,作为开始,我会在GetKeyDown() 方法中使用Keycode.Space 而不是"Jump",因为它消除了调试时必须检查的变量。

    如果还是不行,请随时在这里写评论告诉我。

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 1970-01-01
      • 2018-06-25
      • 2022-11-03
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多