[英]Player not jumping. Unity RigidBody2D
When I press my jump key, the player doesn't jump but the Debug message I added does print in console.当我按下跳转键时,播放器不会跳转,但我添加的调试消息会在控制台中打印。
My code:我的代码:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Start is called before the first frame update
private Transform transform;
private Rigidbody2D rb;
private bool onground = false;
public float speed;
public float momentum;
public float jumpForce;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
transform = rb.transform;
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveHorizontal, 0, 0);
transform.position += movement * Time.deltaTime * speed;
if (Input.GetButtonDown("Jump") && onground)
{
Jump(jumpForce);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Floor")
{
onground = true;
Debug.Log("Player Is On Ground!");
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag == "Floor")
{
onground = false;
Debug.Log("Player Is Not On The Ground!");
}
}
private void Jump(float force)
{
rb.velocity = Vector2.up * force * Time.deltaTime;
Debug.Log("Player Has Jumped!");
}
}
the player can move but not jump and haven't found any posts anywhere with a similar issue, I might not be looking hard enough or searching the correct thing but I just cannot find a solution to my problem.玩家可以移动但不能跳跃,并且在任何地方都没有找到任何有类似问题的帖子,我可能没有足够努力地寻找或搜索正确的东西,但我找不到解决问题的方法。
First of all, you move the player by transform
component but trying to jump by physics ( rigidbody
), it isn't a good idea and I recommend you to work only with rigidbody
in this case.首先,您通过transform
组件移动玩家,但尝试通过物理( rigidbody
)跳跃,这不是一个好主意,我建议您在这种情况下只使用rigidbody
。 Also the multiply jump force by Time.deltaTime
doesn't have a sense because you call the method from FixedUpdate()
, I assume that the power of jump is too week to see the result so try to remove Time.deltaTime
and increase the jumpForce
value.此外, Time.deltaTime
的乘法跳跃力没有意义,因为您从FixedUpdate()
调用该方法,我假设跳跃的力量太周而无法看到结果,因此请尝试删除Time.deltaTime
并增加jumpForce
价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.