We (my friends and I) are trying to make our player take damage when he collides with the enemies, but needless to say we are having some difficulties.
The player stops when colliding with the enemy but the health doesn’t go down. Please help?
Note that we are beginners and haven’t attempted a project of this size before.
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour
{
public GUIText healthText;
public GUIText dieText;
private int health;
public float forceSpeed = 0.01f;
public float speed = 5f;
void Start ()
{
health = 12;
SetHealthText ();
dieText.text = "";
}
void FixedUpdate ()
{
if(Input.GetKey ("s"))
{
transform.Translate(-Vector2.up * speed * Time.deltaTime);
}
if (Input.GetKey ("w"))
{
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
if (Input.GetKey ("a"))
{
transform.Translate(-Vector2.right * speed * Time.deltaTime);
}
if (Input.GetKey ("d"))
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, moveVertical);
rigidbody2D.AddForce(movement * forceSpeed);
}
void OnCollosionEnter(Collider other)
{
if(other.gameObject.tag == "Enemy")
{
other.gameObject.SetActive(false);
health = health -1;
SetHealthText ();
}
}
void SetHealthText ()
{
healthText.text = "health" + health.ToString();
if(health == 0)
{
dieText.text = "YOU DIE!";
}
}
}