- Home /
Offsetting Raycasting
I'm experiencing an issue with 3D raycasting in a 2D setting. The player can create a projectile relative to their position, which destroys itself if it hits an enemy and passes damage information to the enemy it hits. The player and enemies cannot collide (enemies, however, cannot overlap each other). The projectile uses raycasting to check for collisions along the x-axis. So the issue is that when the projectile is spawned too close to an enemy, or even inside an enemy, the raycasting will not hit the object and just pass through it.
My attempted solution was to change the axis where collisions would be detected to the z-axis. That, however, requires an offset to point where the raycast begins.
Here is a snippet of the code where I do the raycasting (part of a function called from update):
if (Physics.Raycast(transform.position + new Vector3(0, 0, 5), -Vector3.forward, out hit, Mathf.Infinity, -1))
{
if (hit.transform.tag == "AI")
{
print("Collision Detected On Z-Axis");
hit.transform.GetComponent<AIBehavior>().SendMessage("takeDamage", dmgMod);
Destroy(this.gameObject);
}
}
Should I check the x-axis with this, the collision detection never finds anything which makes me think that adding the vector3 to it is doing something, but I'm still at lost on how to make this work.
Any thoughts?
Answer by FortisVenaliter · May 12, 2015 at 09:28 AM
Honestly, I would add a simple circle-collision check (the size of the projectile) to the first frame to see if it hits anyone other than the shooter. If the circle-collision fails, then switch to the ray. That should make sure that if it starts in an enemy it will still hit them.
Alternately, you could move the origin of the ray the opposite direction to move the origin back, such as:
Vector3 rayFwd = new Vector3(1,0,0);
Ray ray = new Ray(transform.position - (rayFwd * 5), rayFwd);
But that may have unintended consequences of hitting enemies BEHIND the gun, so that may not be ideal.
Interesting idea, I'll give it a shot to see if I like it any better than my current fix of simply raycasting from the player's position when it first starts up to the point where the object itself spawned. That seems to be working well enough, though.
Follow this Question
Related Questions
Basic LineRender Reflection 2 Answers
(Steam VR / Vive) Rigidbody moving in only one direction after collision 1 Answer
Instantiate after collision 2 Answers
Collision.contacts? 1 Answer