Hello. So I’m trying to make an enemy attack my player through raycast (I tried to use boxcast but the result was the same) but the bools I created shows that it’s hitting the player and the scenary that I’ve created at the same time and I don’t know why. How could I fix it?
I’m not good coding, so it’s basically a frankenstein.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
[SerializeField] Transform barrel;
public GameObject bullet;
public float timerShoot = 2f, sightRange;
float curTimer = 0;
public LayerMask whatIsPlayer;
public LayerMask whatIsCenario;
public bool playerInSightRange, cenarioRange;
// Start is called before the first frame update
void Awake()
{
}
// Update is called once per frame
void FixedUpdate()
{
GameObject player = GameObject.Find("PlayerTop");
transform.LookAt(player.transform);
RaycastHit hit;
//playerInSightRange = Physics.BoxCast(barrel.position, transform.localScale /5, transform.TransformDirection(Vector3.forward), out hit, Quaternion.identity, sightRange, whatIsPlayer, QueryTriggerInteraction.Ignore);
//cenarioRange = Physics.BoxCast(barrel.position, transform.localScale /5, transform.TransformDirection(Vector3.forward), out hit, Quaternion.identity/*transform.rotation*/, sightRange, whatIsCenario, QueryTriggerInteraction.Ignore);
playerInSightRange = Physics.Raycast(barrel.position, transform.TransformDirection(Vector3.forward), out hit, sightRange, whatIsPlayer);
cenarioRange = Physics.Raycast(barrel.position, transform.TransformDirection(Vector3.forward), out hit, sightRange, whatIsCenario);
if ((!playerInSightRange && cenarioRange))
{
curTimer = 0;
}
if (playerInSightRange && !cenarioRange)
{
curTimer += Time.deltaTime;
if(curTimer >= timerShoot)
{
GameObject obj = Instantiate(bullet, barrel.position + transform.forward * 2f, Quaternion.identity);
Destroy(obj, 4f);
curTimer = 0;
}
}
}
}
Here are some images:
If i’m behind a wall and within range, PlayerInSightRange and CenarioRange returns true.
If out of range, it returns false.
If it within range and there’s nothing from the scenery behind the player, the enemy will attack(these are tomato bullets)
If there is scenery behind the player, the enemy will not shoot.