- Home /
Cast ray relative to the direction my Object is moving
Hello, I want to cast a ray to the floor to detect what type of road my car is riding on. I tried something like this: Vector3 direction = -transform.up + new Vector3(1, 0, 0)
(because I want my direction to be a little "tilted", not perfectly perpendicular with the road), but if my object is moving from an opposite direction the ray will be wrong; I would need something like Vector3 direction = -transform.up + new Vector3(-1, 0, 0)
.
The same problem if I want my ray to always point to the left of my object. I'm pretty sure this is something relative to the front direction of my object and a cross product, but I can't find the exact solution.
Answer by Taylor-Libonati · Apr 09, 2019 at 09:12 PM
Instead of hard coding a vector you need to get the direction the car is already moving. Luckily there is a handy function for that. You can do something like this:
Vector3 carForward = transform.forward; //Get the direction the transform is facing
carForward.y = 0;//Ignore the y because you don't want that to influence the height
Vector3 direction = -transform.up + carForward;
direction = direction.Normalized() * distanceToCheck; //OPTIONAL: I suggest normalizing and multiplying so that you can control how far you want this check to go
Thanks a lot! In the third line, by forwardDir
, did you mean the carForward
declared above?
I edited my answer to reflect this. Glad it helped!