Untitled
unknown
csharp
2 years ago
2.7 kB
7
Indexable
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 5f;
public int attackDamage = 10;
public float attackRange = 1f;
public LayerMask enemyLayers;
public int maxHealth = 100;
public int currentHealth;
public int itemsCollected = 0;
private Rigidbody2D rb;
private Animator animator;
public Text healthText;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
currentHealth = maxHealth;
healthText.text = "Health: " + currentHealth;
}
private void Update()
{
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && Mathf.Abs(rb.velocity.y) < 0.001f)
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
if (Input.GetButtonDown("Fire1"))
{
Attack();
}
}
private void Attack()
{
animator.SetTrigger("Attack");
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(transform.position, attackRange, enemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
animator.SetTrigger("Hurt");
if (currentHealth <= 0)
{
Die();
}
healthText.text = "Health: " + currentHealth;
}
public void SetHealth(int value)
{
currentHealth = value;
}
private void Die()
{
animator.SetTrigger("Die");
this.enabled = false;
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Item"))
{
itemsCollected++;
Destroy(collision.gameObject);
}
if (collision.CompareTag("HealthPickup"))
{
Heal(20);
Destroy(collision.gameObject);
}
}
private void Heal(int amount)
{
currentHealth = Mathf.Min(currentHealth + amount, maxHealth);
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
Editor is loading...