I'm making a top-down shooter. I understand the basic raycasting wiki article, but I still don't know how to make the gun not go along the Y-Axis, but just the x/z
When you construct the ray by a conventional method (such as in using Mouse.Hit
and some Part.Position
on the character or on the Player
's gun to compute a direction), you can isolate the x-z plane by removing the y component of the vector and then normalising the new vector.
Normalisation of a vector is when the direction of the vector stays the same, but the magnitude (length) of the vector is set to 1. A normalised vector is also known as a 'unit' vector. Anything in mathematics described as 'unit' means that it is one, basic, standard length. For example, a unit circle is a circle with a radius of 1. A unit square is a square with sides of length 1.
The function below takes a vector, deletes the y-component (by creating a new vector where the y-component is set to 0) and then normalises the vector so that it can be used more conveniently in ray casting.
function LockVectorToHorizontalPlane(v) return Vector3.new(v.X, 0, v.Y).unit end
Vector3.unit
is part of the default ROBLOX implementation of the Vector3 data structure, more info here.
You can construct a ray like this:
positionToShootFrom = ... directionToShoot = ... --You set these parameters range = 200 --How long the ray is, set this to the range of your gun ray = Ray.new(positionToShootFroom, LockVectorToHorizontalPlane(directionToShoot) * range)