Face Nearest Block
There is a constructor of the CFrame datatype that initializes the CFrame based on a two Vector3 positions. The first position is the location of the CFrame, and the second is the point in which the CFrame should be pointed at.
Example: Make Part0 face Part1
local part0 = game.Workspace.Part0
local part1 = game.Workspace.Part1
part0.CFrame = CFrame.new(part0.Position, part1.Position)
The next challenge is determining the distance between two positions. This turns out to be quite simple as Roblox supplies the magnitude method for Vector3 datatypes. This method will give you the distance from the origin to the specified Vector3 position. To get the distance between two points, you simply subtract one point from the other and take the magnitude of the result.
Example: Distance between Part0 and Part1
local part0 = game.Workspace.Part0
local part1 = game.Workspace.Part1
local distance = (part0.Position - part1.Position).magnitude
Now, with what we've learned, we can make a specific part 'look at' the closest part to it if a part is within a certain distance.
Solution: Make a part face nearest block
local parts = game.Workspace.Parts:GetChildren()
local part = game.Workspace.Part
local function faceNearestBlock(part, blocks, maxDistance)
local closestPart
local minDistance = maxDistance
for _, partToFace in ipairs(parts) do
local distance = (part.Position - partToFace.Position).magnitude
if distance < minDistance then
closestPart = partToFace
minDistance = distance
end
end
if closestPart then
part.CFrame = CFrame.new(part.Position, closestPart.Position)
end
end
faceNearestBlock(part, parts, 100)
Positioning a Model
As for positioning a model, the best way to do it is to set the PrimaryPart of the model and use the method SetPrimaryPartCFrame as it will let you avoid some math. If you are curious about how it is done, take a look through the Local and World Space section of the CFrame article on the Wiki.
1 comment
Also my question does not involve mouse, only a object provided in Workspace and detected by the part's script if it has a specific object value.