Issue with firing function, it is correctly pointing and shooting towards walls when my mouse is hovering over them, but when I aim mouse at floor or roof, the Y-value in the direction seems to have an issue and shoots the part towards an incorrect spot, here is the code I am working with:
local function shootPart(part)
if not mouse.Target then
return
end
local targetPosition = mouse.Target.Position
local direction = (targetPosition - part.Position).Unit
local lookVector = CFrame.lookAt(part.Position, targetPosition)
part.CFrame = lookVector
local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.Velocity = direction * 50
bodyVelocity.MaxForce = Vector3.new(500000, 500000, 500000)
bodyVelocity.Parent = part
wait(5)
part:Destroy()
end
Any ideas how to fix this so it calculates direction correctly towards the mouse when pointing at floor/roof/etc?
You’re referencing the position of the part your mouse clicked, instead of where your mouse actually clicked. Mouse.Hit returns the CFrame of where your mouse clicked.
Code:
local function shootPart(part)
local targetPosition = mouse.Hit.Position
local direction = (targetPosition - part.Position).Unit
local lookVector = CFrame.lookAt(part.Position, targetPosition)
part.CFrame = lookVector
local bodyVelocity = Instance.new("BodyVelocity")
bodyVelocity.Velocity = direction * 50
bodyVelocity.MaxForce = Vector3.one * 500000
bodyVelocity.Parent = part
task.wait(5)
part:Destroy()
end
By the way, you should also be using LinearVelocity instead, since BodyVelocities are deprecated.
Code (you could pre-create the attachment as an alternative to creating it in the script):
local function shootPart(part)
local targetPosition = mouse.Hit.Position
local direction = (targetPosition - part.Position).Unit
local lookVector = CFrame.lookAt(part.Position, targetPosition)
part.CFrame = lookVector
local attachment0 = Instance.new("Attachment")
attachment0.Parent = part
local linearVelocity = Instance.new("LinearVelocity")
linearVelocity.RelativeTo = Enum.ActuatorRelativeTo.World
linearVelocity.Attachment0 = attachment0
linearVelocity.VectorVelocity = direction * 50
linearVelocity.MaxForce = 500000
linearVelocity.Parent = part
task.wait(5)
part:Destroy()
end