I have code which is meant to allow the player to interact with objects by pressing the E key. This has worked for most objects in my game so far but when trying to implement ammo pick ups in the form of small 9mm rounds it stopped working.
Using Debug.Log statements I can see that the ray cast seems to be able to hit everything in the scene apart from the round. The round is on the same Default layer as all my other interactable objects.
void FixedUpdate() {
//leave interaction check
interactionEnding = false;
if (interacting)
{
if (Input.anyKeyDown)
{
leaveInteraction();
}
}
float distance = Vector3.Distance(player.position, transform.position);
//interaction check
if (distance <= radius)
{
//if E pressed and not currently leaving an interaction
if (Input.GetKeyDown(KeyCode.E) && !interactionEnding)
{
Ray ray = new Ray(player.position, player.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log("ray hit " + hit.transform.name);
if (hit.collider.gameObject == gameObject)
{
interact();
}
}
}
}
}
Initially I thought the round was too small to be hit so in order to debug I scaled it up 10x. Still when I face the round and try to interact the debug console returns “ray hit wall(34)” essentially meaning that the ray passes through the round and hits the wall behind it.
The round has the Interactable script component which contains the above code along with a box collider which surrounds the mesh.
I hope these images help:
The inspector. As you can see the layer is set to default. Ignore the odd size dimensions as these don’t seem to affect the issue
The round itself with the box collider wrapped around perfectly. The round is depth shaded and as the unity editor doesn’t display depth shading it appears matte grey however most objects in my game are also depth shaded so this shouldn’t affect anything either