How to make an object stick to a surface

Hi, how can i make an object stick to the wall using raycast.

Example:
untitled

2 Likes

You can get the Raycast.position from the variable being returned from workspace:Raycast() and then apply an AlignPosition between the part and the position.

are there different solutions?

Not sure, but there could be other constraints other than AlignPosition that may work for you, I feel like maybe AlignPosition will be your best bet though especially if you want to move the part afterwards.

I would love to give you a code snippet example but I don’t have the time right now., haha.

1 Like

I am no expert but I think this should work.
You can set a new variable to CFrame.lookat(ray.Position, ray.Position+ray.Normal) (ray.Normal is the direction the interesected face is looking).

Now just set the parts cframe to that CFrame + Half of the parts size on the Z axis and it should be correctly placed and rotated.

Example:

local Part = --Your part
 local cf = CFrame.lookAt(ray.Position, ray.Position + ray.Normal)
Part.CFrame = cf + cf.LookVector*(Part.Size.Z/2)
2 Likes

Ok, I’ll try that later when I have time

Instead of that, raycast, and use the normal to figure out the direction the surface is pointing, then you can weld the part to the object.

I don’t know how to calculate the direction the surface is pointing.

If that’s what you’re talking about, then my attempt to help you would be:

Find the intersection position between the object and the wall, and then take the rotation of the wall and rotate the object in the same direction.

local rayOrigin = script.Parent.Position
local rayDistination = workspace.greenWall.Position

local rayLenght = Vector3.new(-100,0,0)

local raycastResult = workspace:Raycast(rayOrigin, rayLenght)

script.Parent.Position=raycastResult.Position
script.Parent.Rotation = raycastResult.Instance.Rotation

Wow, i didn’t know it was that simple. Thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.