Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Am I just dumb or does anyone else not understand this math in guns?

Hello. I have this code:

local mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()
    local Bullet = Instance.new("Part")
    Bullet.Parent = game.Workspace
    Bullet.CanCollide = false
    Bullet.CFrame = game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame * CFrame.Angles(0,math.rad(90),0)
    local Direction = (mouse.Hit.Position - game.Players.LocalPlayer.Character.HumanoidRootPart.Position).Unit
    Bullet.AssemblyLinearVelocity = Direction*100
end)

The line I am intersted in is:

local Direction = (mouse.Hit.Position - game.Players.LocalPlayer.Character.HumanoidRootPart.Position).Unit

That line and this give the same result:

local Direction = (mouse.Hit.Position).Unit

I don't understand why we need to use the first one? Can anyone explain the math?

1 answer

✓ Accepted answer

All of this has to do with Vector Math. When you use Vector3 Coordinates, and you basically draw one point to another, you create a Vector. A vector, compared to a coordinate, represents where it is going (a direction).

When you draw out point A to point B, you create a Vector. This is why when you did:

mouse.Hit.Position - game.Players.LocalPlayer.Character.HumanoidRootPart.Position

You are creating a Vector. This vector has a direction. mouse.Hit.Position is point B and the HumanoidRootPart is point A. You put Point B first as it is larger than Point A, but it doesn't really matter where you put it as the result is positive either way.

Every vector has something called a magnitude (also known as length). Basically you making the length, and then scaling it down to one unit (hence why you did .Unit and not .Magnitude). Once it is scaled down to one unit, you can multiply it to change the range.

If you want to know how to get the magnitude, it is utilising the Pythagoras Theorem in 3D. To get the unit, you divide the Vector positions by the Magnitude of the vector.

1 comment

0

Thank you

This discussion is preserved as it was. New answers, comments, and votes are closed.