我一直在跟随指南,我一直在几十个论坛中跋涉,随后,我一直在撕掉我剩下的头发!
正如您在代码中看到的,我正在尝试使用速度进行移动,并使用 AddForce 进行跳跃 Action 。如果我使用速度,它会跳得超快并且达到最大值,我只是不希望这种情况发生。我想要一个平滑的跳跃,更真实,所以我看到它说用 AddForce 代替。除了……它甚至根本不起作用,他现在就是不跳……什么都没有。
我以速度工作。代码是 rb.velocity = jumping * jumpForce;
就像我说的,这很有效,但它跳得快得离谱,而且看起来一点也不正确。
public class PlayerController : MonoBehaviour
{
public float speed = 3.0f;
public float jumpForce = 4.0f;
public Rigidbody2D rb;
public Vector2 movement;
public bool isJumping;
public Animator animate;
public Vector2 jumping = new Vector2(0,1);
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
//animate = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
//animate.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
moveCharacter(movement);
jumpCharacter();
}
void moveCharacter(Vector2 direction)
{
rb.velocity = direction * speed;
}
void jumpCharacter()
{
if(Input.GetKey(KeyCode.Space) && !isJumping)
{
isJumping = true;
rb.AddForce(jumping * jumpForce);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isJumping = false;
rb.velocity = Vector2.zero;
}
}
}
最佳答案
我遇到过和你一样的情况,我发现使用
Rigidbody2D.velocity =+ Vector2.up * force;
在FixedUpdate()
- 代替
Rigidbody2D.AddForce(Vector2.up * force);
可以工作。
但是我也想知道为什么AddForce
不能正常工作。
关于c# - Rigidbody2D 中的 AddForce 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55879622/