Shoot raycast in direction player is facing

My goal is to shoot a Raycast in the direction the player is facing that goes 50 studs, however, I do not know how to do this. I can’t find anyone else with this issue either.

This is my current code, but it does not work.

local rayOrigin = player.Character.HumanoidRootPart.Position
local rayDirection = player.Character.HumanoidRootPart.CFrame.LookVector
		
local raycastResult = workspace:Raycast(rayOrigin, rayDirection)
print(raycastResult)

It prints ‘nil’, even If I’m facing a wall.

Any help would be appreciated for this.

3 Likes

This is because you’re not constantly printing the updated result, but you’re only printing the result when it’s first established. To test, instead do this:

local rayOrigin = player.Character.HumanoidRootPart.Position
local rayDirection = player.Character.HumanoidRootPart.CFrame.LookVector

while task.wait() do
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection)
	print(raycastResult)
end

what difference will this make?
you are only adding a loop to something that is considered nil

1 Like

It prints at the start of the script, when I presume the character isn’t facing the wall.

Thanks for the reply, but I probably should have mentioned that this code occurs when you push the ‘F’ key.

Could you show me the script with the input handling in eyesight?

Hi, your problem is, that you’ve not defined how far your ray should cast.

Also, LookVector gives a vector3 value that has its x, y, z coordinates between 0-1, multiply the value by a huge amount and face the wall.

Correct me if I am wrong. But doesn’t .LookVector give you a normalized Vector (values 0 to 1) you can just multiply it by 50 to take the range of the ray into account:

local direction = LookVector * 50;

Here you go:

local Length = 50
local raycastResult = workspace:Raycast(rayOrigin, rayDirection*Length)

Edit: Tagged the wrong one.

2 Likes

Thank you so much! This appears to work perfectly!

You should not make the casting of your ray longer than necessary, so “multiplying the value by a huge amount” is a bad idea.

A huge amount to debug, that’s the whole point of my post and by huge amount, I meant a value like 50-100.

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