- Home /
sendMessage doesn't work on objects while the object is behind the sender's transform
Edit: I've made a revalation.
It turns out that the raycast will actually work properly if the edge that the ray is supposed to hit is in view of the camera. Unfortunately, that isn't always something that can be seen, and for whatever reason, when that edge is not visible, the raycast doesn't collide or something, and it won't hit as a result. Is there any way to ensure that the raycast hits an unrendered side of an object?
As shown in the above image, I have a number of cubes. Each of the five cubes has a method called "takeDamage", and an int as an argument. The player has a weapon which fires a projectile, and onCollisionEnter, it overlaps a sphere to check if objects of type "Enemy" are in a radius. After it finds all the objects in that sphere, it raycasts towards them in order to make sure objects which don't register as "enemy" are in the way of the explosion.
What is puzzling to me about why this isn't working is that the objects directly behind the projectile's contact point receive the relevant error, the two red highlights representing the cubes behind the projectile. I tried rotating around 90 degrees and instead it didn't hit the two cubes on the right. If I simply sendMessage takeDamage with the overlapSphere, it works fine.
Here is my code, maybe somebody knows what I'm doing wrong and can help me fix my error.
private void OnCollisionEnter(Collision collision)
{
grenadeBody.constraints = RigidbodyConstraints.FreezeAll;
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.SendMessage("takeDamage", 125);
}
//if grenade directly hits enemy, deals additional damage.
Collider[] collisionPoints = Physics.OverlapSphere(transform.position, 1.5f, overlapLayer);
//bool targetReached = false;
for(int i = 0; i < collisionPoints.Length; i++)
{
Vector3 rayPos = transform.position;
Vector3 dir = collisionPoints[i].transform.position - transform.position;
Debug.DrawRay(rayPos, dir, Color.cyan, 10f);
if (Physics.Raycast(rayPos, dir, out RaycastHit explosiveHit))
{
explosiveHit.collider.SendMessage("takeDamage", 225);
}
}
//somehow, sendMessage(takeDamage, int) doesn't work on objects which are behind the transform.position.
Destroy(this.gameObject);
}
testEnemy.cs (the receiver):
int health;
// Start is called before the first frame update
void Start()
{
health = 1000;
}
private void takeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
print("Enemy died. Health value: " + health);
Destroy(this.gameObject);
}
}
}
Edit: I don't know if I mentioned this but overlapSphere and then sendMessage(takeDamage) to each collider works perfectly, but I need the raycasts. So why is it that the sphere detects everything properly, and can send messages fine, but the second a raycast is involved, it works against whatever is in front of it but not what is behind it?