Unity 2D Платформер LayerMask

2075 / Unity / 2D / Гравець / Платформер LayerMask

 

PlatformerLayerMask2D PlatformerLayerMaskShoot2D
  • Додаємо колайдер
  • Додаємо Rigidbody2D: Gravity Scale = 3, Freeze Rotation z
  • Всередину Player-а додаємо Пустий об'єкт Ground під ногами
  • Додаємо шар Ground платформам
  • В скрипті вказуємо шар Ground і об'єкт GroundCheck

 

Глюки

  • об'єкт Ground ловить ваш колайдер, якщо шар Default

 

public float speed = 8;
public float jumpPower = 24;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
private Rigidbody2D rb;
private float horizontal;
private bool isFacingRight = true;

void Start()
{
  rb = GetComponent<Rigidbody2D>();
}

void Update()
{
  horizontal = Input.GetAxisRaw("Horizontal");

  if (Input.GetButtonDown("Jump") == true && IsGrounded() == true)
  {
    rb.velocity = new Vector2(rb.velocity.x, jumpPower);
  }

  if (Input.GetButtonUp("Jump") == true && rb.velocity.y > 0f)
  {
    rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
  }

  Flip();
}

void FixedUpdate()
{
  rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
}

bool IsGrounded()
{
  return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
}

void Flip()
{
  if (isFacingRight == true && horizontal < 0f || isFacingRight == false && horizontal > 0f)
  {
    isFacingRight = !isFacingRight;
    Vector3 localScale = transform.localScale;
    localScale.x *= -1;
    transform.localScale = localScale;
  }
}