Skip to content
Snippets Groups Projects

Fix/pet attacker

Merged Alifia Rahmah requested to merge fix/pet-attacker into main
Compare and
2 files
+ 68
6
Preferences
Compare changes
Files
2
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
 
using UnityEngine.AI;
public class PetAttack : MonoBehaviour
public class PetAttack : MonoBehaviour
{
{
public int damage = 10;
public int damage = 10;
public int timeBetweenAttack = 10;
public int timeBetweenAttack = 10;
public float range = 2f;
 
public float detectRadius = 2f;
 
 
float timer;
 
PetHealth petHealth;
Animator anim;
Animator anim;
 
RaycastHit raycastHit;
 
int shootableMask;
void Start()
void Awake()
{
{
anim = GetComponent<Animator>();
anim = GetComponent<Animator>();
 
petHealth = GetComponent<PetHealth>();
 
shootableMask = LayerMask.GetMask("Shootable");
}
}
// Update is called once per frame
// Update is called once per frame
void Update()
void Update()
{
{
timer += Time.deltaTime;
 
 
// Spherecast to detect enemy
 
if (Physics.SphereCast(transform.position, detectRadius, transform.forward * range, out raycastHit, range, shootableMask))
 
{
 
// Face the hit enemy
 
Vector3 targetDir = raycastHit.transform.position - transform.position;
 
transform.rotation = Quaternion.LookRotation(targetDir);
 
 
// Attack
 
EnemyHealth enemyHealth = raycastHit.collider.GetComponent<EnemyHealth>();
 
if (enemyHealth != null)
 
{
 
AttackEnemy(enemyHealth);
 
}
 
}
}
}
// TODO: use raycast instead of collider
void OnTriggerEnter(Collider other)
void OnTriggerEnter(Collider other)
{
{
EnemyHealth enemyHealth = other.GetComponent<EnemyHealth>();
EnemyHealth enemyHealth = other.GetComponent<EnemyHealth>();
if (enemyHealth != null)
AttackEnemy(enemyHealth);
 
}
 
 
public void AttackEnemy(EnemyHealth enemyHealth)
 
{
 
if (timer >= timeBetweenAttack && enemyHealth != null && petHealth.currentHealth > 0)
{
{
 
// Reset timer
 
timer = 0f;
 
anim.SetTrigger("Attack");
anim.SetTrigger("Attack");
//Lakukan Take Damage
//Lakukan Take Damage