Trying to cast a ray from part A to part B. Simple, right?
Wrong. Literally nothing I’m trying is detecting part B, and I have no idea why.
local s = game.Selection:Get()[1]
local s2 = game.Selection:Get()[2]
local ray = Ray.new(s.Position, s2.Position)
local prt = game.Workspace:FindPartOnRay(ray)
print(prt)
nil
WHAT? What am I doing wrong? I’ve tried this code a million times with many different parts in many different areas and it still shows nil. I can’t take it anymore. Help please!
The Ray’s second parameter isn’t a position to face towards, it’s a LookVector. You can get the LookVector from one position to another using CFrame.fromMatrix like in this sample found on the devhub: (which I creatively slapped .LookVector onto)
function lookAt(target, eye)
local forwardVector = (eye - target).Unit
local upVector = Vector3.new(0, 1, 0)
-- You have to remember the right hand rule or google search to get this right
local rightVector = forwardVector:Cross(upVector)
local upVector2 = rightVector:Cross(forwardVector)
return CFrame.fromMatrix(eye, rightVector, upVector2).LookVector
end
Then, you should be able to use what that returns as the second parameter to Ray.new.
The second argument in the Ray.new() constructor is the direction in which the ray is supposed to go. The direction given must be with respect to the origin of the ray, not the absolute origin of the world. The direction of a vector v3 from v1 to v2 is given by the equation
v3 = v2 - v1
-- Unit vector:
v3 = (v2 - v1).Unit
Applying this with the absolute origin case,
v3 = v2 - (0,0,0)
=> v3 = v2
This is what you’re feeding, a direction with respect to the origin. When the ray attempts to follow this direction and translating the direction it to its own origin, the resultant direction is a vector parallel to the world direction, not identical.
To fix this you simply change where your direction is from:
ray = Ray.new(s.Position, (s2.Position - s.Position))