RayCast not casting on mouse position properly

I’m trying to make a projectile using RayCast however when I try to spawn a part on my mouse just to check if the Ray is working properly, it spawns in a somewhat random spot as you can see in this video,

video

My Code:

local plr = game.Players.LocalPlayer
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local humRP = char:WaitForChild("HumanoidRootPart")

local RS = game:GetService("ReplicatedStorage")
local Debris = game:GetService("Debris")
local UIS = game:GetService("UserInputService")


local debounce = false
local CD = .1

local tpRemote = RS.Remotes.Teleport

local mouse = plr:GetMouse()

local KEY = Enum.KeyCode.V

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {char}



local function throwKunai()
	
	local kunai = RS.FX.RaijinKunai:Clone()
	
	local rayOrigin = humRP.Position
	local rayDirection = mouse.Hit.Position

	local raycastResult = game.Workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	
	if raycastResult == nil then return

	end
	
	local objHit = raycastResult.Instance
	
	local spawnPart = Instance.new("Part")
	spawnPart.Position = raycastResult.Position
	spawnPart.Parent = workspace.Map.Ignore
	
	print("Pressed V")
	
end

UIS.InputBegan:Connect(function(inp, gpe)
	if gpe then return end
	if inp.KeyCode == KEY and not debounce then
		debounce = true
		throwKunai()
		task.wait(CD)
		debounce = false
	end
end)
1 Like

The direction of the Raycast is added to its origin. This means that in your code, the direction parameter of the :Raycast() is set as rayOrigin + rayDirection behind the scenes. That’s why when we want to simply cast a Ray downwards, we set the direction parameter as Vector3.new(0, -10, 0); because the end position of the Ray will just be [Ray origin] + Vector3.new(0, -10, 0).

I’ve had the same issue in my game before. You can simply fix it by making the direction parameter be rayDirection - rayOrigin. Which supposedly will, behind the scenes, be rayOrigin + (rayDirection - rayOrigin).

1 Like

Ah that makes so much sense, also preciate the explanation it helped out alot. :+1:

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