Reputation: 21
Im trying to make 2 types of enemies, melees and ranged, so im trying that both have a raycast to the player to know if they can see the player and are enought near, but I have two problems. The first one is that when I check the distance between the enemy and the player is always 0, and the second is that Raycast doesnt print when it should. Let me explain, Im in front of the enemies and it prints that sees me, but other times not, in the same conditions, so i dont know what im missing.
Here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMelee : EnemyBase {
public int rangoAttack;
RaycastHit hit;
int layerMask = 1 << 2;
void Update () {
perseguir();
attackMele();
}
void attackMele() {
if (Physics.Raycast(transform.position, player.transform.position, layerMask)){
print(hit.distance);
}
Debug.DrawLine(transform.position, player.transform.position, Color.red);
}
}
Enemies are on Layer 2
Pd: EnemyBase script just have movement to the player with nav.SetDestination (player.position);
Image of the enemy (cant upload images yet): https://ibb.co/eq7pMV
Upvotes: 1
Views: 749
Reputation: 1228
First problem occurs because you don't use hit
in the code. So hit.distance = 0
.
Second problem occurs because in Physics.Raycast(transform.position, player.transform.position, layerMask)
you should set direction in 2nd argument (Not endpoint). You can calculate direction by this: Vector3 direction = player.transform.position - transform.position
.
Try this code:
RaycastHit hit;
int layerMask = 1 << 2;
public float maxDistance;
void Update ()
{
attackMele();
}
void attackMele()
{
Vector3 direction = player.transform.position - transform.position;
if (Physics.Raycast(transform.position, direction, out hit, maxDistance, layerMask))
print(hit.distance);
Debug.DrawLine(transform.position, player.transform.position, Color.red);
}
I hope it helps you.
Upvotes: 1