How to shoot a raycast EXACTLY right or left

I need to fire a raycast from my player, which is a spaceship, EXACTLY right or left.

Not right or left relative to the player’s orientation, but right or left relative to the world. The player’s orientation changes a lot, so when I shoot a ray right or left, using Vector3.right or Vector3.left, it’s very often pointing downward or upward.

Is there a way I can fire a ray that totally disregards the player’s rotation, even though it’s firing from the player?

Here’s the relevant portion of the code:

Vector3 raycastDirection;
if (movingRight)
    raycastDirection = Vector3.right;
else
    raycastDirection = Vector3.left;

RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(raycastDirection), out hit, Mathf.Infinity, ground))
{
    Debug.DrawLine(transform.position, hit.point, Color.red);
    proximityDistance = hit.distance;
}

2 Answers

2

Vector3.right literally just gives you (1, 0, 0). This is exactly right from the world coordinate point of view. transform.right is relative to a specific transform’s orientation. Are you sure that Vector3.right is giving you something other than 1,0,0?

Or maybe a better question is, "exactly right" from who's point of view?

–

From the world's point of view is what I'm trying for.

–

I’m sure. I even substituted it with new Vector3(1, 0, 0) just to make sure. Same result. But the raycast is coming from an object that is rotated. I was considering creating another game object that mirrors the ship’s position only, but I’m certain there’s an easier way.

Post your code so we can see it.

–

You should be able to edit your original post and use the </> button to create a region to paste code.

–

Also, why are you doing "transform.TransformDirection" on the raycastDirection if you just want the raw Vector3.left direction?

–

I haven't done a lot of raycasting before. I think I got that from a scripting example. What should I put there instead?

–