- Home /
Question by
Hjalpmovie · Apr 30, 2013 at 08:27 PM ·
enemydeathlosehealth
How can I lose health when my enemy collides with the player?
Soo... I'm creating a simple game. The player has 10 health-points and the enemy 100 (dies on 6 hits). I want to make it so the player lose health every tick if the enemy is touching it. Just a simple collide thing.
Player code:
var curHealth : int = 100;
var maxHealth : int = 100;
var healthtext : GUIText;
function Start () {
healthRegen();
}
function Update () {
healthtext.text = curHealth + " / " + maxHealth;
if(curHealth < 1 ) {
curHealth = 10;
Application.LoadLevel ("Death");
}
if(curHealth > 100) {
curHealth = 100;
}
if(Input.GetKeyDown("e")) {
curHealth -= 1;
}
if(Input.GetKeyDown("m")) {
Application.LoadLevel ("MainMenu");
}
}
// CODE THAT DOES NOT WORK! WHY?
function OnCollisionEnter(collision : Collision){
if(collision.CompareTag("Enemy")){
//Reduce global health var
curHealth -= 1;
}
}
function healthRegen () {
for(i=1;i>0;i++) {
yield WaitForSeconds(2.5);
if(curHealth < maxHealth) {
curHealth++;
}
}
}
Enemy Code:
var Distance;
var Target : Transform;
var lookAtDistance = 25.0;
var chaseRange = 15.0;
var attackRange = 1.5;
var moveSpeed = 5.0;
var Damping = 6.0;
var attackRepeatTime = 1;
private var attackTime : float;
var controller : CharacterController;
var gravity : float = 20.0;
private var MoveDirection : Vector3 = Vector3.zero;
function Start ()
{
attackTime = Time.time;
}
function Update ()
{
Distance = Vector3.Distance(Target.position, transform.position);
if (Distance < lookAtDistance)
{
lookAt();
}
if (Distance > lookAtDistance)
{
renderer.material.color = Color.green;
}
if (Distance < attackRange)
{
attack();
}
else if (Distance < chaseRange)
{
chase ();
}
}
function lookAt ()
{
renderer.material.color = Color.yellow;
var rotation = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
}
function chase ()
{
renderer.material.color = Color.red;
moveDirection = transform.forward;
moveDirection *= moveSpeed;
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
function attack ()
{
if (Time.time > attackTime)
{
Debug.Log("Basic");
attackTime = Time.time + attackRepeatTime;
}
}
function ApplyDammage ()
{
chaseRange += 5;
moveSpeed += 0.013;
lookAtDistance += 6;
}
Please help :(
Comment
Answer by sfc.itzhak · Apr 30, 2013 at 10:27 PM
look here and see if this helps you http://forum.unity3d.com/threads/84715-Collision-with-enemy-lose-health
sfc
I looked at it, I don't understand "//Reduce global health var here"... :(
Your answer
Follow this Question
Related Questions
Enemy health. Need to take damage from two different bullet prefabs 1 Answer
Death upon health = 0 2 Answers
I need some health with my health/enemy script 0 Answers
Player Health and Death 1 Answer
Enemy Health Help 1 Answer