Your mouse is repeatedly hitting a point on the model, and setting the model to that point. That’s why it flies to the camera. Use raycasting instead and exclude the player character and the model you’re placing from the raycast parameters.
You could also set the Mouse.TargetFilter to the model, but then you would be able to point onto your character as well. Using raycasts is the ideal way as you can ignore multiple objects.
local localPlayerCharacter = Players.LocalPlayer.Character
local mouse = Players.LocalPlayer:GetMouse()
local mouseRay = mouse.UnitRay
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = { model, localPlayerCharacter }
local raycast = Workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 128, raycastParams)
Raycasting can also follow CollisionGroup rules. You could make a group just for model placement raycasts and have it not collide with any player character and itself.
local player = game:GetService('Players').LocalPlayer
local replicated = game:GetService("ReplicatedStorage")
local run = game:GetService("RunService")
local uis = game:GetService("UserInputService")
local cas = game:GetService("ContextActionService")
local replicatedTowers = replicated.Towers
local childrenOfFrame = script.Parent.Tower1:GetChildren()
local CanPlace: boolean = true
local Tower: Model;
local mouse = player:GetMouse()
local ImageButton: ImageButton
local rotateButton = script.Parent.Parent:WaitForChild("Rotate").Frame.Rotate
for i,v in pairs(childrenOfFrame) do
if v:IsA("ImageButton") then
ImageButton = v
end
end
function rotateTower()
Tower:PivotTo(Tower:GetPivot() * CFrame.Angles(0,math.rad(90),0))
end
ImageButton.MouseButton1Click:Connect(function()
if CanPlace then
Tower = replicatedTowers[ImageButton.Name]:Clone()
Tower.Parent = workspace.Towers
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = {Tower, player.Character}
run.RenderStepped:Connect(function()
local mouseRay = mouse.UnitRay
local raycast = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 512, raycastParams)
Tower:PivotTo(CFrame.new(raycast.Position))
end)
if uis.KeyboardEnabled then
cas:BindAction("Rotate", rotateTower, false, Enum.KeyCode.R)
else
script.Parent.Parent:WaitForChild("Rotate").Enabled = true
end
rotateButton.MouseButton1Click:Connect(function()
rotateTower()
end)
end
end)