I’m trying to get a raycast to go out from my player and then rotate with the player.
ive got the raycast going and the player rotating, but the raycast stays in the same place.
this will eventually be a character that seeks objects in the scene by rotating untill the raycast hits an object with a certain tag, then goes to the position of that object.
i’m decent enough with C# but i’m new to unity so any help is appreciated.
Use transform.forward for the direction.
As you can see in the documentation, Physics.Raycast takes an origin point, which is a Vector3 that represents a point in space. That should be your character or it’s eyes or whatever you use to cast the ray from. However, the direction parameter is a bit tricky - while it’s a Vector3 it’s not a position in space, but rather the vector itself.
To get a direction from two vectors you need to subtract one from the other so you’ll get the direction from the point you subtracted to the point you subtracted from.
For example: A-B = the direction from B to A, while B-A = the direction from A to B.
It sounds confusing but you can understand it if you simplify it down to a Vector1: 3-6 gives you negative 3, which is the direction from 6 to 3, while 6-3 will give you positive 3 which is the direction from 3 to 6.
Considering this, all you have to do is make another game object slightly ‘in front’ of the origin point and make it a child of the character object so it will turn with it. Then in your Raycast you pass the parameters as follows:
Physics.Raycast(originPoint.position, Vector3.Normalize(slightlyForwardPoint.position-originPoint.position), rayDistance);
Alternatively, if you’re certain you’ll always be casting it forward (Z axis) you can pass
transform.TransformDirection(Vector3.forward) as the direction.
EDIT: Forgot to mention that you’ll want to normalize the direction, otherwise you might get weird behaviors like extremely long rays.