GameObject 不会在向刚体添加力时跳跃

分享于2022年07月17日 c# unity3d-2dtools 问答
【问题标题】:GameObject 不会在向刚体添加力时跳跃(GameObject doesn't jump on adding force to rigidbody)
【发布时间】:2022-07-08 06:49:58
【问题描述】:

我尝试让角色在加力时跳跃

public class DemonController : MonoBehaviour
{
 [SerializeField]
 private float speed;
 [SerializeField]
 private Rigidbody2D rb;
 [SerializeField]
 private Animator anim;
 [SerializeField]
 private float jumpForce;
 [SerializeField]
 private SpriteRenderer sr;

 private Vector2 movement;

 // Update is called once per frame
 void Update()
 {
    movement.x = Input.GetAxisRaw("Horizontal");
 }

 void FixedUpdate() {
    Move();
    Jump();
    Attack();
 }

 void Move()
 {
   if (movement.x > 0) {
       sr.flipX = false;
   } else if (movement.x < 0) {
       sr.flipX = true;
   }
   anim.SetBool("running", movement.x != 0);
   rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime); 
}

void Jump()
{
    if (Input.GetKeyDown("space")) {
        Debug.Log("space pressed");
        rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }
}

void Attack()
{
    if (Input.GetKeyDown(KeyCode.J)) {
        anim.SetTrigger("attack");
    }
}
}

这真的很有趣,因为我可以移动和攻击,但我不能跳跃。跳转的条件是正确的,因为记录了“按下空格”。 我也尝试添加 Y 速度,但它也不起作用。有人知道解决这个问题吗?

character inspector1 character inspector2

  • 你的弹跳力是多少,可能还不够
  • 我尝试将其设为 100,但它甚至没有反应

【解决方案1】:

我想我明白了。此行会导致问题:

rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime); 

MovePosition 函数,根据文档,通过给它一个速度来移动对象的位置,使其在一帧中到达所需的位置。这会干扰跳跃产生的力量,有效地压倒你跳跃的力量。不应在同一帧中同时使用 AddForce 和 MovePosition。