Having trouble with teleporting the player

I’m using raycast to detect if there is an object in front of the player, if there is then the player will teleport to that object’s position, if there isn’t the player will teleport 20 studs ahead. There appears to be no problem when there is an object, but when there isn’t the player doesn’t teleport 20 studs ahead, but instead teleports to a random position.

Here’s the code

Local:

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local root = character:WaitForChild("HumanoidRootPart")

local UIS = game:GetService("UserInputService")

local fireRay = game.ReplicatedStorage.FireRay

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.E then
		fireRay:FireServer(root)
	end
end)

Server:

local fireRay = game.ReplicatedStorage.FireRay

fireRay.OnServerEvent:Connect(function(player, root)
	local character = player.Character or player.CharacterAdded:Wait()
	local rayParams = RaycastParams.new()
	rayParams.FilterDescendantsInstances = {character, workspace.Baseplate}
	rayParams.FilterType = Enum.RaycastFilterType.Exclude
	local ray = workspace:Raycast(root.Position, root.CFrame.LookVector * 20, rayParams)
	if ray then
		print(ray.Instance)
		root.CFrame = ray.Instance.CFrame
	else
		warn("no object ahead!")
		root.Position = root.CFrame.LookVector * 20
	end
end)
4 Likes

You are only checking if the ray exists, not if there is a part ahead, try if ray.Instance then instead of if ray then

3 Likes

It doesn’t work, if ray then does detect if there is a part ahead I think

3 Likes

try to make else condition, when there is nothing, move 20 studs but if there is player, then move 20 studs, it can be solution

3 Likes

I already did that. The problem here is that when there isn’t an object ahead, the player doesn’t teleport 20 studs ahead but rather teleports somewhere else

2 Likes

can you try adding root.Position then multiply root.CFrame.LookVector by 20

root.Position = root.Position + root.CFrame.LookVector * 20
2 Likes

Sorry for the late reply. Sadly it doesn’t work :frowning:

now it teleports the player far away from the map for some reason