我可以以某种方式编写此代码进行优化吗? 如果不使用协程,则当我单击空格时,下一个跳转将具有更大的作用力,依此类推。 如果使用rb.MovePosition,角色将以15 fps的速度移动。我知道,请更改设置中的时间。但是我想知道是否存在另一种方法...
private void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
StopAllCoroutines();
StartCoroutine(Jump());
}
}
private IEnumerator Jump() {
if(rb.bodyType != RigidbodyType2D.Dynamic) {
rb.bodyType = RigidbodyType2D.Dynamic;
}
rb.constraints = RigidbodyConstraints2D.FreezePositionY;
_pos = transform.position;
for (float t = 0; t < 1; t += Time.deltaTime * 4f)
{
transform.position = Vector3.Lerp(transform.position, new Vector3(transform.position.x, _pos.y + .35f, transform.position.z), t);
yield return null;
}
rb.constraints = RigidbodyConstraints2D.None;
}
答案 0 :(得分:0)
存在刚体,因此您无需直接调整对象的变换。由于您拥有Rigidbody2d
,因此可以直接设置速度:
public float jumpSpeed = 5f; // Whatever feels right
private void FixedUpdate() {
if(Input.GetKeyDown(KeyCode.Space)) {
rb.velocity = Vector2.up * jumpSpeed;
}
}
(已编辑为使用velocity
而不是AddForce
)