Strange raycast behavior

I’m trying to let the player teleport a small distance when they press Q on their keyboard. To avoid players teleporting through walls, I cast a ray from the player’s HumanoidRootPart and detect if it’s touching any parts. If it is, the player will teleport to the hit position of the ray, otherwise, they will teleport the full distance.

The problem is that the ray is returning unexpected hit positions. Here is a video demonstrating this, the green ray is the expected behavior and the red ray is the actual behavior.



Here is my code for the wall check

function CheckForWall()
	local rayDir = Vector3.new(
		HumanoidRootPart.Position.X + (HumanoidRootPart.CFrame.LookVector.X * 15),
		HumanoidRootPart.Position.Y,
		HumanoidRootPart.Position.Z + (HumanoidRootPart.CFrame.LookVector.Z * 15)
	)
	
	local ray = workspace:Raycast(
		Vector3.new(HumanoidRootPart.Position),
		rayDir - Vector3.new(HumanoidRootPart.Position)
	)
	print(ray)
	
	if ray then
		CreateLine(HumanoidRootPart.Position, ray.Position)
		return ray.Position
	else
		return Vector3.new(
		HumanoidRootPart.Position.X + (HumanoidRootPart.CFrame.LookVector.X * 15),
		HumanoidRootPart.Position.Y,
		HumanoidRootPart.Position.Z + (HumanoidRootPart.CFrame.LookVector.Z * 15)
	)
	end
end

And here is my code for the teleportation:

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.Q then
		-- Move
		Character:MoveTo(CheckForWall()) -- here
		
		-- Effect
		local newEffect = EffectObject:Clone()
		newEffect.Parent = HumanoidRootPart
		newEffect.CFrame = HumanoidRootPart.CFrame * CFrame.new(Vector3.new(0, 0, 8))
		newEffect.ParticleEmitter:Emit()
		
		Debris:AddItem(newEffect, 1)
	end
	if input.KeyCode == Enum.KeyCode.E then
		CheckForWall()
	end
end)

Remove the Vector3.new from these, when Vector3.new is passed an invalid argument for any of its axes, it’ll default to 0. Vector3.new expects 3 numbers, not a Vector3, so both of these are defaulting to 0, 0, 0

On a side note, you can shorten this quite a bit if you want,

workspace:Raycast(
    HumanoidRootPart.Position,
    HumanoidRootPart.CFrame.LookVector * Vector3.new(1, 0, 1) * 15
)
1 Like

Thank you! It works perfectly now.

1 Like

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