Get the position one stud in front of a RaycastResult?

Hi, I’m creating NPCs. When the player clicks on an NPC and nothing blocks his path, he walks towards it. But the problem is, the player gets way too close to the NPC. So I’d like to stop the player 1 stud in front of the RaycastResult…

function attackNPC.attackNPC(player: Player, NPC: Model)
	local character: Model? = if player.Character then player.Character else nil
	local humanoid: Humanoid? = if character and character:FindFirstChildOfClass("Humanoid") then character:FindFirstChildOfClass("Humanoid") else nil
	local primaryPart: BasePart? = if character and character.PrimaryPart ~= nil then character.PrimaryPart else nil
	if not character or not humanoid or not primaryPart then return end
	
	local NPCPrimaryPart: BasePart? = if NPC.PrimaryPart ~= nil then NPC.PrimaryPart else nil
	if not NPCPrimaryPart then return end
	
	print(player.Name.." is now attacking "..NPC.Name)
	
	local rayOrigin: Vector3 = primaryPart.Position
	local rayDestination: Vector3 = NPCPrimaryPart.Position
	
	local rayDirection: Vector3 = rayDestination - rayOrigin
	
	local raycastParams: RaycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {character}
	
	local raycastResult: RaycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	if not raycastResult then return end
	
	humanoid:MoveTo(raycastResult.Position)
end
1 Like

Idk if this is the best way but it is a way,

local rayDirection: Vector3 = (rayDestination - rayOrigin).Unit * (rayDestination - rayOrigin).Magnitude - 1
1 Like

It seems to create an error in my script:

Try

local rayDirection: Vector3 = (rayDestination - rayOrigin).Unit * ((rayDestination - rayOrigin).Magnitude - 1)
1 Like

It’s working now, however the Humanoid only seems to actually move 1 out of 10 times when I click the NPC?

Sorry, instead of cutting the ray 1 stud short, revert it to what it was and replace this

with this

humanoid:MoveTo(rayOrigin + (raycastResult.Position - rayOrigin).Unit * ((raycastResult.Position - rayOrigin).Magnitude - 1))
1 Like

Why so many calculations? Wouldn’t this be enough:

humanoid:MoveTo(raycastResult.Position + (rayOrigin - raycastResult.Position).Unit)
1 Like

Yeah, you’re right!
image

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.