Ray Casting Along Local Axis

Hey, I’m trying to make a cube detect an object by ray casting. I have it casting a ray by Vector3.forward, so along its z axis. After detecting an obstacle it is supposed to rotate a random amount and then move off in that direction until it detects another obstacle and then it repeats. However, the ray it’s casting stays pointing in the direction of the global z axis and not the cubes local z axis. Everything works, except that the ray doesn’t turn with the cube, which causes a lot of detection problems after the first one. Basically, why isn’t it rotating with the cube? I thought that rays defaulted to local axis. Here is some of my script:

function [COLOR="#4169e1"]Update[/COLOR](){
	
	[COLOR="blue"]var[/COLOR] hit : [COLOR="#4169e1"]RaycastHit[/COLOR];
	
	[COLOR="lime"]//If the ray detects something[/COLOR]
	[COLOR="blue"]if[/COLOR]([COLOR="#4169e1"]Physics[/COLOR].[COLOR="#4169e1"]Raycast[/COLOR]([COLOR="#4169e1"]transform[/COLOR].[COLOR="#4169e1"]position[/COLOR], [COLOR="#4169e1"]Vector3[/COLOR]([COLOR="red"]0[/COLOR], [COLOR="red"]0[/COLOR], [COLOR="red"]1[/COLOR]), hit, [COLOR="red"]1[/COLOR])){
		[COLOR="lime"]//This just calls another function. Could be replace by anything.[/COLOR]
                ObstacleAvoidance();
        }
}

Okay, I got it working. Apparently, in order for the ray to be cast in the local direction, you have to create a variable for the direction and use that instead. For example:

[COLOR="navy"]var [/COLOR]forward = [COLOR="#4169e1"]transform[/COLOR].[COLOR="#4169e1"]TransformDirection[/COLOR]([COLOR="#4169e1"]Vector3[/COLOR].[COLOR="#4169e1"]forward[/COLOR]);

Then do this:

[COLOR="navy"]If[/COLOR]([COLOR="#4169e1"]Physics[/COLOR].[COLOR="#4169e1"]Raycast[/COLOR]([COLOR="#4169e1"]transform[/COLOR].[COLOR="#4169e1"]position[/COLOR], forward, hit, [COLOR="red"]1[/COLOR])){
      DoSomeThingHere();
}

No, just do

if (Physics.Raycast (transform.position, transform.forward, hit, 1)) {

–Eric

1 Like

Thanks! I didn’t know you could do that.:smile: