Raycast Returns as Nil

I’m trying to make a bomb for my game, and today I’ve decided I wanted to make a way that the bombs can plant themselves. I would’ve done this by raycasting by the player’s height and then I made the bomb go to the designated position, though it’s not working and instead returns as nil when I print the instance.

The code goes as follows:

UserInputService.InputBegan:Connect(function(input, gpe)
	if input.KeyCode == Enum.KeyCode.R then
		print("e")
		local bombPlantPosition
		local rayParams = RaycastParams.new()
		rayParams.FilterType = Enum.RaycastFilterType.Exclude
		rayParams.FilterDescendantsInstances = {Tool.Parent}
		
		local raycastResult = workspace:Raycast((Tool.Handle.CFrame * CFrame.new(0, 0, 2)).Position, Vector3.new(0, -5, 0), rayParams)
		
		local castingRay = true
		
		print("b")
		
		while castingRay do task.wait()
			print("a")
			raycastResult = workspace:Raycast((Tool.Handle.CFrame * CFrame.new(0, 0, 2)).Position, Vector3.new(0, -5, 0), rayParams)
			print(raycastResult)
			
			if raycastResult ~= nil then
				print("o")
				bombPlantPosition = raycastResult.Position
				print(bombPlantPosition)
				
				castingRay = false
				
				if not cooldown then 
					cooldown = true

					RemoteEvent:FireServer(Player, bombPlantPosition)

					UserInputService.MouseIcon = RELOADING_ICON

					task.wait(5)

					UserInputService.MouseIcon = MOUSE_ICON

					cooldown = false
				end
			end
		end
	end
end)

I suggest spawning a part at Tool.Handle.CFrame * CFrame.new(0, 0, 2).Position and another one 5 studs down from that make sure that the origin and direction are correct.

1 Like

What do you expect this offset to do? Depending on the size and orientation of the tool Handle part, and height of your character, the origin of the raycast could easily be more than 5 studs above the ground. I agree with MrShowerMan that you should double check that the ray origin is where you think it is, and that the ray is long enough.

1 Like

My initial thought where to just use the CFrame for the position, and I didn’t take rotation into consideration, I’ve already gotten the height of the character and it is about 5 studs tall.

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