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
How to make a raycast ray that ony goes across the x/z axis?
1 answer
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)
5 comments
Thanks, I'll try it out, I'll further comment if I run into any problems
If you don't have any trouble understanding what I've written, or don't have any questions directly related to your original question, then don't forget to up-vote this answer.
Actaully, what should I set the values of positionToShootFrom/directionToShoot to??
It depends: Some people will project a ray from the tip of the gun, but in your top-down game you can probably just use the character's torso. In that case, the position is the position of the torso, and the direction is a unit vector that goes from the torso to the the world-position of the mouse.
In other words: Get a reference to the mouse using 'mouse = game.Players.LocalPlayer:GetMouse()' and get a reference to the player's torso. Then positionToShootFrom is torso.Position and directionToShoot will be (mouse.Hit - torso.Position).unit
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
An Example script would be nice.