Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make a raycast ray that ony goes across the x/z axis?

Asked by 9 years ago

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

0
An Example script would be nice. woodengop 1134 — 9y

1 answer

Log in to vote
0
Answered by
duckwit 1404 Moderation Voter
9 years ago

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)
0
Thanks, I'll try it out, I'll further comment if I run into any problems spartanttravis 0 — 9y
0
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. duckwit 1404 — 9y
0
Actaully, what should I set the values of positionToShootFrom/directionToShoot to?? spartanttravis 0 — 9y
0
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. duckwit 1404 — 9y
0
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 duckwit 1404 — 9y
Ad

Answer this question