【发布时间】:2018-02-19 00:24:54
【问题描述】:
我正在学习 Unity,并且正在编写播放器脚本。根据我编写的脚本,我希望看到我的玩家能够在静止不动、向左移动和向右移动时跳跃。 如果同时向右移动,玩家将无法跳跃。我做了一堆重构和重组。我认为这可能与Input.GetButton("Jump") 有关。
另外,我将rb2d.AddForce(new Vector2(0.0f, jumpHeight)) 更改为rb2d.velocity = new Vector2(0.0f, jumpHeight),但播放器就消失了。
到目前为止,这是我的脚本:
private Rigidbody2D rb2d;
[SerializeField]
private LayerMask whatIsGround;
private bool isTouchingGround;
private bool facingRight = true;
[SerializeField]
private float speed;
[SerializeField]
private float jumpHeight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
float moveHorizontal = Input.GetAxis("Horizontal");
Flip(moveHorizontal);
if (Input.GetButton("Jump") && IsGrounded()) {
rb2d.AddForce(new Vector2(0.0f, jumpHeight));
}
rb2d.velocity = new Vector2(moveHorizontal * speed, rb2d.velocity.y);
}
private void Flip(float horizontal) {
if ((horizontal > 0 && !facingRight) || (horizontal < 0 && facingRight)) {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private bool IsGrounded() {
if (rb2d.velocity.y <= 0) {
foreach (Transform point in groundPoints) {
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
foreach (Collider2D collider in colliders) {
if (collider.gameObject != gameObject)
return true;
}
}
}
return false;
}
【问题讨论】: