![](/img/trans.png)
[英]I am making a 2d platformer game in unity engine, but I am unable to make my player jump
[英]I'm trying to make a simple 2d platformer game, but my code wont let me jump
这是我在 C# 中的第一场比赛,我不知道该怎么做,因为评论中没有人提到我见过的任何内容。
这是我写的确切代码。
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# 的新手,这对我有很大帮助。 :)
为了检测玩家的接地状态,我只需使用您可以在脚本中实现的 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"
,因为它消除了调试时必须检查的变量。
如果它仍然不起作用,请随时在这里写评论并让我知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.