why does my enemy shoot through walls?

my enemy can shoot through walls? I’m guessing I need a raycast. Help!

var Distance;
var Target : Transform;
var ShootRange = 25.0;
var attackRange = 15.0;
var moveSpeed = 5.0;
var Damping = 6.0;
var projectile : Rigidbody;
var fireRate : float = 1;
var FireRange = 0-100;
private var nextFire : float = 0.0;
function Update ()
{
        Distance = Vector3.Distance(Target.position, transform.position);
      
        if (Distance < ShootRange)
        {
                GetComponent.<Renderer>().material.color = Color.yellow;
                lookAt();
        }
      
        if (Distance > ShootRange)
        {
                lookAt();
              
        }
      
        if (Distance < attackRange)
        {
                GetComponent.<Renderer>().material.color = Color.red;
                attack ();
        }
      
        if (Distance > attackRange && Time.time > nextFire )
        {
        nextFire = Time.time + fireRate;
                Instantiate(projectile, transform.position, transform.rotation);
              
        }
}
function lookAt ()
{
        var rotation = Quaternion.LookRotation(Target.position - transform.position);
      
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
                      
      
      
}
function attack ()
{
        transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}

2333540--157656--screenshot.jpg

What is the attached screenshot? Is it the projectile?

Is the problem you want to fix that the projectile is moving through the wall, or that the enemy is firing at the wall when the player is on the other side of it?

If it’s the first, have your projectile get destroyed when it collides with a wall.

If it’s the second, then a raycast can work. If the raycast hits a wall before the player, it would mean the wall is in the way. If you only want the raycast to only look for certain things, you can use layers.

The screenshot is the enemy shoot script and the problem is that the projectile goes through walls. Should I change the layer of the wall to something and if the projectile collides with it then destroy the game object?

Yeah, if you want to make projectiles not go through something, you’ll have to detect collision with that thing and then make your projectile blow up or get destroyed or whatever you want it to do. Layers are intended for raycasts and cameras, I think, so you might want to use tags, so you could either create a ‘wall’ tag, or if there are multiple objects you don’t want it to be able to pass through, something like an ‘unpassable’ tag. But note that you can only have one tag per object so use what works best for your game.

hax.

1 Like

thanks but I fixed the problem, the bullet was travelling too fast for the colliders to catch up