Making a CFrame face towards a ray?

I’ve been attempting to make a part tween towards a ray position, which I’ve done but the problem is the orientation keeps facing towards somewhere else. I’ve tried to fix this and I’ve spent about an hour on it researching and trying different methods but same thing.

If you still don’t know what I mean, I want the part to face the ray intersection point which I have it doing initially, but it changes once it reaches that point.

Making it face towards it at the start:

CFrame.new(part.Position, -ray.Position)

What it’s tweening to (where it’s messing up)

CFrame.new(ray.Position)

I know I’m missing something which is why it’s not working but I can’t figure out what.

I have an idea but I’m not sure it’s the cleanest solution, but it might work.

The idea is to take the orientation of the part after you set its CFrame to look at the intersection point, and preserve it as the part is tweened to said point.

--//CFrame the part to look at the intersection point here^
local comp = {somePart.CFrame:components()}
local intersectionPoint = positionFromRay --//This would be the variable that contains the position that the ray hit
local goalCFrame = CFrame.new(intersectionPoint.X, intersectionPoint.Y, intersectionPoint.Z, unpack(comp))

Tried this already but did it again to confirm, still messes up. This time it faces downward

I actually messed up the code.

Try this and tell me what happens:

local tween = game:GetService("TweenService")

local targetPosition = pos --//Input the hit position of the ray here

local comp = {somePart.CFrame:GetComponents()}
local rotation = {}

for i = 4, #comp do --//Only grab rotation values from CFrame components
	table.insert(rotation, comp[i])
end

--//Construct new CFrame containing the positional coordinates from the ray position, but preserve the part's orientation
local goalCFrame = CFrame.new(targetPosition.X, targetPosition.Y, targetPosition.Z, unpack(rotation))

tween:Create(somePart, TweenInfo.new(4), {CFrame = goalCFrame}):Play()

I just tested this and it worked fine for me.

1 Like

It faces towards the ground instead of the intersection point

https://gyazo.com/6c860ab9cbcf91164aa008f982577e4b

Found the problem, your code actually did work fine. I was using a custom tween service to tween the model and tried just tweening the part and it worked as it should.

1 Like