Quantcast
Channel: Questions in topic: "die"
Viewing all articles
Browse latest Browse all 115

how to take health/hearth from player when colliding with an object?

$
0
0
I'm working on a 2d sidescrolling shooter, but I can't figure out how to take damage from the player when hitting something (a projectile or an enemy). I have a 4 heart health system and if the player gets hit by something, then 1 heart is gone, if all 4 hearts are gone, the player dies. unfortunately... this doesn't work. Nothing happens to the hearts... Help! this is the Health Script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Health : MonoBehaviour { public int PlayerHealth = 4; public int numOfHearts = 4; public int damage = 1; public Image[] hearts; public Sprite fullHeart; public Sprite emptyHeart; public GameObject deathEffect; public void TakeDamage(int damage) { PlayerHealth =- damage; if (PlayerHealth == 0) { Die(); } void Die() { Instantiate(deathEffect, transform.position, Quaternion.identity); Destroy(gameObject); } } public void Update() { if (PlayerHealth > numOfHearts) { PlayerHealth = numOfHearts; } for (int i = 0; i < hearts.Length; i++) { if (i < PlayerHealth) { hearts[i].sprite = fullHeart; } else { hearts[i].sprite = emptyHeart; } if (i < numOfHearts) { hearts[i].enabled = true; } else { hearts[i].enabled = false; } } } public void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Projectile") { PlayerHealth =- damage; } } } I can't figure out what I'm doing wrong... Also here are the scripts of the enemyprojectile and the enemy: using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyProjectile : MonoBehaviour { public float moveSpeed = 7f; public int damage = 100; public GameObject ImpactEffect; Rigidbody2D rb; PlayerMovement2 target; Vector2 moveDirection; void Start() { rb = GetComponent(); target = GameObject.FindObjectOfType(); moveDirection = (target.transform.position - transform.position).normalized * moveSpeed; rb. velocity = new Vector2 (moveDirection.x, moveDirection.y); Destroy(gameObject, 3f); } void OnTriggerEnter2D (Collider2D col) { if (col.gameObject.name.Equals("Player")) { Debug.Log("Hit!"); Destroy(gameObject); Instantiate(ImpactEffect, transform.position, transform.rotation); } } } using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public Transform player; public int health = 400; public GameObject deathEffect; public void TakeDamage(int damage) { health -= damage; if (health <= 0) { Die(); } void Die() { Instantiate(deathEffect, transform.position, Quaternion.identity); Destroy(gameObject); } } }

Viewing all articles
Browse latest Browse all 115

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>