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

How do you calculate a Vector3 a few studs in front of an object?

I am making a(n) (FPS) gun and want to have the raycast start from the muzzle of my gun and have the DIRECTION be a few studs in FRONT of the muzzle. I have no idea how to do this. Here is my code attempt (in a Localscript):

	local RAY_PARAMS = RaycastParams.new()
	RAY_PARAMS.FilterDescendantsInstances = IgnoredParts
	RAY_PARAMS.FilterType = Enum.RaycastFilterType.Blacklist

	local dir = Muzzle.Position * Vector3.new(0, 0, 2)

	local RAY_RESULT = workspace:Raycast(Muzzle.Position, (dir - Muzzle.Position).Unit * WeaponData.Range, RAY_PARAMS)

When I try this method, the ray only fires in one direction no matter where I turn the gun. Any ideas on how to fix this?

Yes, I have tried CFrame.LookVector and it still gives me the same results.

EDIT:

This is what the code with LookVector looks like:

	local RAY_PARAMS = RaycastParams.new()
	RAY_PARAMS.FilterDescendantsInstances = IgnoredParts
	RAY_PARAMS.FilterType = Enum.RaycastFilterType.Blacklist

	local dir = Muzzle.CFrame.LookVector * 2

	local RAY_RESULT = workspace:Raycast(Muzzle.Position, (dir - Muzzle.Position).Unit * WeaponData.Range, RAY_PARAMS)

And yes, the muzzle CFrame is redefined every frame the game renders (via. RenderStepped). Still doesn't work.

3 comments

0

I see no reason why CFrame.LookVector wouldn't work, what did your code using LookVector look like?

0

You need to redefine the lookVector each time you cast a ray. Otherwise it keeps using the same, old position.

0

To everyone reading this, read my answer below.

1 answer

And the reason why it doesn't work? Simple. On line 5 of the code above, it should be:

local dir = Muzzle.CFrame + Muzzle.CFrame.LookVector

I can't believe I mad such a silly mistake.

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