I want to know how to make a specific block always face towards the nearest object in Workspace with a value. I do not know what I should use in this case besides probably lookVector. Also how would you do this with a model too? (don't feel like welding the parts together to the main part that rotates)
Also, if you could do this too, how would I define the distance variable? I would not want a part facing towards a part from infinite studs. (I don't really need this too much but it would be appreciated so I wouldn't have to add more code)
ex: a knight is always suspicious of you so when your nearby (assuming a variable which the distance between the knight and the player will activate the script) so he will always face you to ensure you do not do anything bad
Note: I am not good at probably moving models but maybe you could use for i,v in ipairs(model:GetChildren()) do and then rotate the children altogether but I don't know if this would look good or not.
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
-- Assuming `Parts` is a model in workspace containing all potential parts to face 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)
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.