in a nutshell:
i’m making aiming down sights, it was working very well but then i wanted to make the aimpart always end up on the same “axis” as the mouse:
this would ensure that the “aimpart” is always on center of the screen, and i wouldn’t have to manually adjust its position in studio
friend of mine suggested to use linear algebra (i tried raycasting and it didn’t work lol),
so i did use it
this is really confusing to me idk why the offset is like this
-- setup lerp variables
local lerpAlpha = 0
local lerpSpeed = 1.5
-- lerp viewmodel
rService:BindToRenderStep("AimGun", Enum.RenderPriority.Camera.Value, function(deltaTime)
-- calculate alpha
lerpAlpha = math.clamp(lerpAlpha + lerpSpeed * deltaTime, 0, 1)
-- get parameters for calculating intersection point
local camPos = camera.CFrame.Position
local mouseOrigin = mouse.Origin.Position
local mouseDirection = mouse.UnitRay.Direction.Unit
-- calculate intersection point
local distanceToCamera = mouseOrigin - camPos
local projectedVector = distanceToCamera:Dot(mouseDirection)
local intersectionPoint = mouseOrigin + projectedVector * mouseDirection
-- calculate offset
local aimpartOffset = intersectionPoint - viewmodelAimPart.Position
local offset = camera.CFrame:ToObjectSpace(CFrame.new(viewmodelAimPart.Position + aimpartOffset)).Position
-- calculate new cframe
local targetCFrame = camera.CFrame * CFrame.new(-offset)
local currentCFrame = viewmodel:GetPivot()
local lerpedCFrame = currentCFrame:Lerp(targetCFrame, lerpAlpha)
-- pivot the viewmodel to the lerped cframe
viewmodel:PivotTo(lerpedCFrame)
end)