- Home /
Enemy attack and player health!
Hi, I was wondering if some one new how to make it so that the enemy in this script:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform player;
public float playerDistance;
public float rotationDamping;
public float moveSpeed;
public static bool isPlayerAlive = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (isPlayerAlive) {
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 5000f) {
lookAtPlayer ();
}
if (playerDistance < 4090f) {
if (playerDistance > 1.8f) {
chase ();
} else if (playerDistance < 1.8f) {
attack ();
}
}
}
}
void lookAtPlayer()
{
Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
void chase()
{
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
void attack()
{
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.forward, out hit))
{
if(hit.collider.gameObject.tag == "Player")
{
hit.collider.gameObject.GetComponent<PlayerHealth>().health -= 5f;
}
}
}
}
has to hit my player 3 times in this script:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public float health;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (health < 0f)
{
EnemyAI.isPlayerAlive = false;
Destroy (gameObject);
}
}
}
and each hit has a 2 secondsin between thx!
Answer by thisisaunityaccount · Jul 12, 2015 at 09:39 PM
A simple way to do this:
public int hitCount = 3; //number of hits
public float hitTime = 2; //time in seconds between each hit
float curTime = 0; //time in seconds since last hit
Then, in Update:
if (hitCount > 0) //if there are more hits left
{
curTime += Time.deltaTime; //add time
}
Then, in your existing ifs in Update:
else if (playerDistance < 1.8f) {
if (curTime >= hitTime ) //if the set amount of time has passed
{
attack ();
}
}
Then, added into attack():
curTime = 0; //reset the time
hitCount--; //subtract one from the hit count
You could optionally add another variable for the number of hits, counting up from 0, instead of subtracting one from hitCount. That'd be useful if you'd need a reloading feature or something similar, where the enemy can only attack three times in a row before needing to do something else.
Lemme know if this works out for you.
hi I don't know where to put the last part into thx 4 now
matthewjparker99 just create a void attack: void Attack() {
}
Your answer
![](https://koobas.hobune.stream/wayback/20220611230910im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
enemy need to stop and shoot while walking on waypoint 0 Answers
Enemy AI problems 2 Answers
rigidbody enemy goes only forward, no damage delay. 2 Answers