I'm trying to figure out a way of casting rays for the sides of my player (character controller.) It's easy enough to fire a ray from the center, but for this particular task I need to be able to fire from the left and right sides of the players bounds.
I thought it would be relatively easy to get the width of the player gameObject and fire the ray from there (offset it from the center) but it seems it isn't nearly as easy I thought. Am I missing something?
I haven't tested this code but I think this method should work,
var characterController : CharacterController;
var characterController = gameObject.GetComponent(CharacterController);
var characterRadius : float = characterController.radius;
var rayOrigin : Vector3;
var hit : RaycastHit;
// Right edge forward facing raycast
rayOrigin = transform.position + transform.right * characterRadius;
if (Physics.Raycast(rayOrigin, transform.forward, hit, 10)) {
// Executed on right side hit
}
// Left edge forward facing raycast
rayOrigin = transform.position - transform.right * characterRadius;
if (Physics.Raycast(rayOrigin, transform.forward, hit, 10)) {
// Executed on left side hit
}
If you have the width, can you not just use that to create a temporary object at that distance either side of the centre, fire the ray from that and then delete it? Or alternatively keep the objects there to save re-creation, depending on how often it needs calculating.