Get mouse position

im pretty new to development and im making a tower defense game however i have been having trouble with getting the mouse position for my placement system, i followed a tutorial and i somewhat got it to work and the part is following my mouse but aside it

please tell me why it is following next to the mouse if you know and how i can fix it, here is my code:

-- local runService = game:GetService("RunService")


local userInputService = game:GetService("UserInputService")
local Camera = workspace.CurrentCamera
local mousePart = workspace:WaitForChild("mousePart")
local RANGE = 1000

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {mousePart}
raycastParams.FilterType = Enum.RaycastFilterType.Exclude

local function render()
	local mouse2DPosition: Vector2 = userInputService:GetMouseLocation()
	local mouse3DRay: Ray = Camera:ViewportPointToRay(mouse2DPosition.X, mouse2DPosition.Y, 1)
	local raycastResult: RaycastResult = workspace:Raycast(mouse3DRay.Origin, mouse3DRay.Direction*RANGE, raycastParams)
	local mouse3DPosition
	
	if raycastResult then
		mouse3DPosition = raycastResult.Position + Vector3.new(0, mousePart.Size.Y*0,5, 0)
	else
		mouse3DPosition = (mouse3DRay.Origin + mouse3DRay.Direction*RANGE) + Vector3.new(0, mousePart.Size.Y*0,5, 0)
	end
	
	mousePart.Position = mouse3DPosition
end

runService.RenderStepped:Connect(render)



Seems like you’ve got a small typo that’s creating this issue:

This is causing the Z value of your Vector3 to be 5 instead of 0. I think you mean:

mousePart.Size.Y * 0.5

Change that for both lines and that should solve the issue.

2 Likes

tysm for the help! cant believe i missed that

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