- Home /
Raycasting from the sides of a GameObject
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?
Answer by Rennat · Dec 02, 2010 at 06:22 AM
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 }
Answer by Novodantis 1 · Aug 07, 2010 at 06:28 PM
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.
I don't have the width as far as I know. It isn't a property of Transform.
Ah, apologies, so you said. Try using mesh.bounds.extents.x
where var mesh : $$anonymous$$esh = GetComponent($$anonymous$$eshFilter).mesh;
Your answer
Follow this Question
Related Questions
Drag Rigid Body No Distance Limit and how to add Mouselock to a scrip 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Get GameObject to face and move towards Raycast hit point 1 Answer
C# Raycast 2D GameObject follow Mouse 1 Answer
Location of raycast collision. 1 Answer