I’m trying to make a sword thing where, when the player presses V and a enemy is in front of him, it gives the enemy damage, but the raycast doesn’t register on the enemy, and the enemy is on the correct layer and tag
using UnityEngine;
public class Sword_Player : MonoBehaviour
{
private EnemyHealth EnemyHPscript;
public Transform PlayerTR;
public int sworddamage;
public int raydistance;
public LayerMask enemyLayer;
private void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.V))
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, PlayerTR.right, enemyLayer, raydistance);
Debug.DrawRay(transform.position, new Vector3(PlayerTR.position.x + 100f, PlayerTR.position.y, PlayerTR.position.z), Color.red);
if (hit.collider.tag == "Enemy")
{
Debug.Log("it hit");
EnemyHPscript = hit.collider.GetComponent<EnemyHealth>();
EnemyHPscript.TakeDamage(sworddamage);
}
}
}
}
and this is the enemyHP script:
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float MaxHP;
private float CurrentHP;
public float timeB4destroyGO;
private void Start()
{
CurrentHP = MaxHP;
}
public void TakeDamage(int damage)
{
CurrentHP -= damage;
if(CurrentHP <= 0) { Die(); }
}
public void Die()
{
Destroy(gameObject , timeB4destroyGO);
}
}