I’m making a game and i’m making an enemy.
I want to make the enemy detect if the player is in range to attack.
I’m using a boxcollider in front of the enemy so when the player is colliding with the boxcollider he attacks.
BUT, the boxcollider doesnt detect the player…
Here is my Code of the enemy:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCombat : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public float attackRange = 0.5f;
public int attackDamage = 40;
//public float attackRate = 2f;
//float nextAttackTime = 0f;
[SerializeField] private float attackCooldown;
[SerializeField] private float range;
[SerializeField] private float colliderDistance;
[SerializeField] private BoxCollider2D boxCollider;
[SerializeField] private LayerMask playerLayer;
private float cooldownTimer = Mathf.Infinity;
private Animator anim;
private void Awake()
{
anim = GetComponent<Animator>();
}
void Update()
{
cooldownTimer += Time.deltaTime;
//Attack only when player in sight
if (PlayerInSight())
{
Debug.Log("HEYYYYYYYYYYYY!");
if (cooldownTimer >= attackCooldown)
{
cooldownTimer = 0;
Attack();
}
}
}
void Attack()
{
animator.SetTrigger("Skeleton_Attack_1");
Collider2D[] hitPlayer = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, playerLayer);
foreach(Collider2D player in hitPlayer)
{
player.GetComponent<PlayerMovement>().TakeDamage(attackDamage);
}
}
private bool PlayerInSight()
{
RaycastHit2D hit = Physics2D.BoxCast(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z),
0, Vector2.left, 0, playerLayer);
//if (hit.collider != null)
//{
// Debug.Log("HEYYYYY!");
// cooldownTimer += Time.deltaTime;
//
// //Attack only when player in sight
// if (cooldownTimer >= attackCooldown)
// {
// cooldownTimer = 0;
// Attack();
// }
//}
return hit.collider != null;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance, new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z));
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
Here it shows the enemy Combat. but the Bool doesnt work. it wont detect if teh player is colliding.
How to fix this?
Help would be Great!!