I’m trying make building system, but I’m stuck on Wedge part’s slope for an entire day, and broke my brain…
Can someone help me, and say, what I’m making wrong with it?
local Wedge = mouse.target
local WedgeSize = Wedge.Size
local WedgeCFrame = Wedge.CFrame
local Position = mouse.Hit.Position
local NullPos = (WedgeCFrame:Inverse() * CFrame.new(Position)).Position
local AC = WedgeSize.Y
local CB = WedgeSize.Z
local AB = (AC^2 + CB^2) ^0.5
local CD = AC * CB / AB --lenght of height
local AD = AC ^ 2 / AB --lenght of projection
local SlopePosition = Vector3.new(0, AC / 2, -CB / 2):Lerp(Vector3.new(0, -AC / 2, CB / 2), Vector3.new(0, AC / 2, -CB / 2) - Vector3.new(0, NullPos.Y, -NullPos.Z)).Magnitude / AB) - AD / AB) + Vector3.new(NullPos.X, 0, 0)
local Angle = CFrame.new(Vector3.new(0, -AC / 2, CB / 2), (CFrame.new(Vector3.new(0, AC / 2, CB / 2), Vector3.new(0, -AC / 2, -CB / 2)) + CFrame.new(Vector3.new(0, AC / 2, CB / 2), Vector3.new(0, -AC / 2, -CB / 2)).LookVector * AD).Position)
Offset = (Angle + (Angle.LookVector * (CD + Part.Size.Z / 2))) + Vector3.new(SlopePosition.X, SlopePosition.Y, SlopePosition.Z)
Part.CFrame = TargetCFrame * Offset
What I want achieve:
But for now, part’s orientation is correct only, position is wrong.
I’m terrible with math, and shouldn’t be giving any ideas, however I feel like a raycast might work? Cast from the bottom of the green part to the wedge part then set the CFrame of the green part to the end of the ray + part.Size/2? Only reason this seems reluctant would be it seems kind of like it could be a quite rare situation to be needed and looks like it might be a pain to implement but sounds easier than generally doing the math for it.
local Part = -- your part.
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {part}
local ray_result = workspace:Raycast(Part.Position, Vector3.new(0,-15,0), params)
if ray_result then
Part.CFrame = CFrame.fromMatrix(ray_result.Position)
end
To rotate a part you can use RaycastResult.Normal which returns the normal where the RaycastResult occurred.
if ray_result then
local look_vec, right_vec, up_vec
up_vec = ray_result.Normal
look_vec = up_vec:Cross(Part.CFrame.rightVector)
right_vec = up_vec:Cross(look_vec)
Part.CFrame = CFrame.fromMatrix(ray_result.Position, right_vec, up_vec, look_vec)
end
Keep in mind that this is just an example and I haven’t tested it, you just need to play around with it.