Raycast in Roblox not hitting what I expect

My raycast for a gun keeps returning nil or hitting the player's own character. I'm passing the direction as the target position. Do I need to subtract the origin, and how do you exclude your own character?
2

Leave A Reply

Log in to post an answer.

2 Answers

john_5 Nov 25, 2026
sakshi_arcade
Check the result before you use it. Raycast returns nil when it hits nothing, so result.Instance throws an error that looks unrelated. When I'm debugging I spawn a thin anchored part along the ray for a second so I can actually see where it's going, that usually shows the problem in one go.
amara Oct 23, 2026
sakshi_arcade
Most of the time it's the direction argument. It isn't a target position, it's a vector whose length is how far the ray goes. So: local dir = (target - origin).Unit * 500 local result = workspace:Raycast(origin, dir, params) If you pass the target's Position as the direction, the ray goes off somewhere random. The second most common cause is the ray hitting your own character or tool first. Set up RaycastParams with FilterType = Enum.RaycastFilterType.Exclude and put your character in FilterDescendantsInstances. Also, parts with CanQuery off are skipped, and invisible parts are not. A transparent hitbox will block the ray unless you exclude it.