First: tab your code correctly. This isn't super hard to do, and it makes code much easier to work with.
Next: use local
variables. It's always a good idea to declare your intent by explicitly declaring variables using local
. It also saves headaches later.
Make your code much easier to read by putting spaces around operators. At the least, spaces around =
and +
make it significantly easier to parse.
distance
is a poor name for a displacement
normDistance
is a poor name for something that's always length 1 -- call it a direction.
dotProduct
is superfluous. Just use direction:Dot(humanoid.Torso.CFrame.lookVector)
Use the two argument Instance.new(class, parent)
to save a line.
Use workspace
instead of game.Workspace
.
Use :FindFirstChild
instead of :findFirstChild
.
EDIT:
hit.Parent.Humanoid
will never be nil
. You will get an error if the object doesn't exist. Use :FindFirstChild("Humanoid")
instead.
It's pointless to use :FindFirstChild("Torso").Position
. The value of not erroring when the torso doesn't exist goes away if you try to ask for the .Position
of nil
. Just use .Torso.Position
, or do proper error checking like it sounds like you need.