RayCast From Centre of Camera
Hey all,
I'm trying to make a RayCast from the centre of my camera, but it's not working properly- it only works if I'm facing a certain direction. My code so far is:
void FixedUpdate() {
RaycastHit hit;
Ray forwardRay = new Ray (player.transform.position, Vector3.forward);
if (Physics.Raycast (forwardRay, out hit, sightDistance)) {
//more code
}
What's going wrong? Thanks so much!
-SM
Answer by Namey5 · Mar 13, 2017 at 06:37 AM
When defining the ray, change the direction from;
Vector3.forward
to;
transform.forward
Otherwise, you are just accessing a constant direction, in this case the world's Z axiz, rather than the Z axis of your object.
That worked perfectly, but how would I make it follow me up and down, so I could, for example, collide with something on the floor?
-S$$anonymous$$
What exactly do you mean? Is the ray staying in the same vertical position? Is it not changing direction with vertical rotation? Without knowing your scene I can't really help. The only thing I can really suggest is if this script is attached to the camera, use;
transform.position
rather than;
player.transform.position
As the ray origin, otherwise the ray will not follow the position of your camera. If it isn't attached to your camera and 'player' is the camera object, then change the direction to;
player.transform.forward