x


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?

more ▼

asked Aug 07 '10 at 06:17 PM

Disaster gravatar image

Disaster
482 49 57 67

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Aug 07 '10 at 06:28 PM

Novodantis 1 gravatar image

Novodantis 1
1.7k 14 22 40

I don't have the width as far as I know. It isn't a property of Transform.

Aug 07 '10 at 06:40 PM Disaster

Ah, apologies, so you said. Try using mesh.bounds.extents.x

Aug 09 '10 at 06:37 PM Novodantis 1

where var mesh : Mesh = GetComponent(MeshFilter).mesh;

Aug 09 '10 at 06:41 PM Novodantis 1
(comments are locked)
10|3000 characters needed characters left

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
}
more ▼

answered Dec 02 '10 at 06:22 AM

Rennat gravatar image

Rennat
664 5 8 18

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5275
x2176
x1948
x1582

asked: Aug 07 '10 at 06:17 PM

Seen: 1914 times

Last Updated: Aug 07 '10 at 06:17 PM