How would i go about doing this. Im doing this so as that i have an alternative to mouse.hit as i only want the mouse ray to ‘hit’ when meeting a given world y coordinate returning the x and z coordinates instead of the mouse ray ‘hitting’ objects and from that getting the x,y,z coordinates of the point.
ive tried getting the mouse rays vector using .Direction and then now im stuck at how to get the x and z coordinates of the vector when given the y
function rayToPlaneIntersection(rayVector, rayPoint, planeNormal, planePoint)
local diff = rayPoint - planePoint
local prod1 = diff:Dot(planeNormal)
local prod2 = rayVector:Dot(planeNormal)
local prod3 = prod1/prod2
return rayPoint - (rayVector*prod3)
end
function findIntersectionWithHeight(rayVector, rayPoint, height)
return rayToPlaneIntersection(rayVector, rayPoint, Vector3.new(0,1,0), Vector3.new(0,height,0))
end
print(findIntersectionWithHeight(Vector3.new(0,1,.5), Vector3.new(0,0,0), 7))
Output: 0, 7, 3.5
This code is used to find the location where a line intersects a plane. A line is defined by a directional vector and a position. A plane is defined by a normal (direction that the face of the plane is pointing) and a position.
I use the line-plane intersection code for your purpose by creating a plane that is at the height where you want to find the intersection point, and with a normal facing up(/down).
Im Back. Thank you so much it works very well. If anyones wondering the rayPoint would be the origin of the ray and the height would be the y coordinate of the plane.
Do you know a way to check if there was no intersection between the vector and the plane?
I believe ive got how but not sure it would work in all situations(in my scenario if prod3 is negative it has intersected and if not it would be positive)
To be technical there’s always an intersection between a ray and a plane, unless they’re exactly parallel (which is a case you might need to handle that the above code doesn’t). I’m guessing what you want to see is if the intersection is in the positive or negative direction along the vector.
function rayToPlaneIntersectionDistance(rayVector, rayPoint, planeNormal, planePoint)
local diff = rayPoint - planePoint
local prod1 = diff:Dot(planeNormal)
local prod2 = rayVector:Dot(planeNormal)
if prod2 == 0 then
return nil -- parallel case
else
local prod3 = prod1/prod2 --> Now we know prod2 isn't zero
return -prod3
end
end
function findIntersectionWithHeight(rayVector, rayPoint, height)
local distance = rayToPlaneIntersectionDistance(rayVector, rayPoint, Vector3.new(0,1,0), Vector3.new(0,height,0))
if distance ~= nil and distance > 0 then
return rayPoint + distance * rayVector
else
return nil
end
end