【发布时间】:2020-02-23 11:56:25
【问题描述】:
所以我试图让我的 2D 角色跳跃。 如果我在地面上跑步,它可以完美运行,但是当我撞到墙壁时,它就会出现问题:我什至可以在空中跳跃。 我试过用 bool 变量解决这个问题,但没有奏效。 我想过检查玩家是否在空中,然后将 is_on_ground 变量设置为 false。 显然,玩家只有在地面上时才应该跳跃。 我的代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour
{
private bool canJump = false;
public SpriteRenderer sr;
private bool facingRight;
private Animator animator;
private bool is_on_ground;
public Button leftBtn;
public Button rightBtn;
public Button jumpBtn;
public float max_velocity;
public float velocity;
public float jump_scalar;
private Rigidbody2D rb;
private float x_movement;
private Vector2 movement;
void Start() {
canJump = true;
facingRight = true;
animator = gameObject.GetComponent<Animator>();
leftBtn.onClick.AddListener(moveLeft);
rightBtn.onClick.AddListener(moveRight);
jumpBtn.onClick.AddListener(jump);
rb = gameObject.GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
if (rb.velocity.magnitude < max_velocity) {
movement = new Vector2(x_movement, 0);
rb.AddForce(movement * velocity);
}
}
private void OnCollisionEnter2D(Collision2D collision) {
if (CollisionIsWithGround(collision)) {
animator.SetBool("isJumping", false);
canJump = true;
}
if (collision.collider.tag == "wall") {
canJump = false;
}
is_on_ground = true;
}
private void OnCollisionExit2D(Collision2D collision) {
if (!CollisionIsWithGround(collision)) {
is_on_ground = false;
}
if (collision.collider.tag == "wall") {
is_on_ground = true;
canJump = true;
}
}
private bool CollisionIsWithGround(Collision2D collision) {
bool is_with_ground = false;
foreach (ContactPoint2D c in collision.contacts) {
Vector2 collision_direction_vector = c.point - rb.position;
if(collision_direction_vector.y < 0) {
is_with_ground = true;
}
}
return is_with_ground;
}
public void moveLeft() {
if (is_on_ground) {
animator.SetBool("isJumping", false);
}
animator.SetBool("isRunning", true);
sr.flipX = true;
facingRight = false;
x_movement = -1;
}
public void onRelease() {
animator.SetBool("isRunning", false);
x_movement = 0;
if(is_on_ground) {
animator.SetBool("isJumping", false);
rb.velocity = Vector3.zero;
}
}
public void moveRight() {
if (is_on_ground) {
animator.SetBool("isJumping", false);
}
if (!facingRight) {
sr.flipX = false;
facingRight = true;
animator.SetBool("isRunning", true);
} else {
animator.SetBool("isRunning", true);
}
x_movement = 1;
}
public void jump() {
if(is_on_ground) {
if (canJump) {
animator.SetBool("isJumping", true);
Vector2 jumpForce = new Vector2(0, jump_scalar * 100);
rb.AddForce(jumpForce);
}
}
}
}
【问题讨论】: