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)