3
\$\begingroup\$

I was planning on using ray casting for collision detection in my game. However, when I use an attack similar to this:

enter image description here

(which would project something like a cylinder), how would I go about detecting if it hits the other player?

\$\endgroup\$
4
\$\begingroup\$

I think this is what you want:

Physics.SphereCast

From the docs:

Casts a sphere against all colliders in the scene and returns detailed information on what was hit.

This is useful when a Raycast does not give enough precision, because you want to find out if an object of a specific size, such as a character, will be able to move somewhere without colliding with anything on the way. Think of the sphere cast like a thick raycast.

It basically tests for collisions against a capsule (cylinder with rounded ends) with a specified start point, direction, radius, and length.

Note that this will not detect collisions with triggers. It will only give you information about the first collision encountered - so if you want the beam to pass through the first target and hit a second/third/etc, you'll want to use Physics.SphereCastAll instead.

\$\endgroup\$
0
\$\begingroup\$

This is typically done with multiple raycasts. The game design dictates the exact pattern needed but a simple one is to just do 4 or so casts at equal distances along the surface of the cylinder. Do all the tests, collect all their results, then take the hit with the shortest distance. Avoid overly small or narrow objects in your design and you don't need to worry about "gaps" in the cylinder's rays.

If the cylinder is particularly wide, add one or more rays, both to the surface and inside.

A similar technique is used for comes and certain scatter weapons, like shotguns.

\$\endgroup\$
0
\$\begingroup\$

Transform key points (see below) of the other player's body into the object space of the cylinder.

Then check whether any of them fall within the axis-aligned bounding box of the cylinder.

If so, then check whether they fall within the cylinder, by checking radial distance from cylinder's axial centre.

Key points to check would be on the other player's extremities, e.g. head, hands, feet, maybe elbows and knees, aside from obviously torso centre.

This will likely be faster than Physics.SphereCast.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.