I am Having some problems with RayCasting

Even though my mouse is pointing at a direction the dummy is going to a different direction.
I am new to using raycasting so I dont know how to fix this problem.

Here is my code

local ReplicatedStorage = game.ReplicatedStorage
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local UserInputService = game:GetService("UserInputService")
local Father = Workspace.Buildings

local camera = Workspace.CurrentCamera
local RealBuilding = nil

local gui = script.Parent
local function MouseRaycast(blacklist)
	local mouseposition = UserInputService:GetMouseLocation()
	local mouseray = camera:ViewportPointToRay(mouseposition.Y, mouseposition.X)
	local raycastParams = RaycastParams.new()
	
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	raycastParams.FilterDescendantsInstances = blacklist
	local raycastResult = Workspace:Raycast(mouseray.Origin, mouseray.Direction * 1000, raycastParams)
	print(mouseposition)
	return raycastResult
end

local function CreateBuilding()
	local Building1 = ReplicatedStorage:WaitForChild("Building1")
	if Building1 then
		RealBuilding = Building1:Clone()
		RealBuilding.Parent = Father
	end
end
gui.Activated:Connect(function()
	CreateBuilding()
end)
RunService.RenderStepped:Connect(function()
	if RealBuilding then
		local result = MouseRaycast({RealBuilding})
		if result and result.Instance then
			print(result.Instance.Name)
			local x = result.Position.X 
			local y = result.Position.Y 
			local z = result.Position.Z 
			
			local cframe = CFrame.new(x,y,z)
			RealBuilding:SetPrimaryPartCFrame(cframe)
			-- Set back to :SetPrimaryPartCFrame() once full model is released
			print(cframe)
		end
	end
end)


Yes, this code is from GnomeCode’s Part 5 video in making a tower defense game

Try mouseray.Direction * 2000, A lot of rays seem to always have this.

1 Like

It still doesn’t work. the error is still there

local mouseray = camera:ViewportPointToRay(mouseposition.X, mouseposition.Y)
You flipped the Y and X, this should fix it.

1 Like

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