local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
mouse.TargetFilter = game:GetService("Workspace"):WaitForChild("RinkTemplate")
local hit = mouse.Hit
with a similar code but with a twist. I want a code which does exactly that but like if the mouse was positioned in the middle of the screen, as I want to utilize the code on mobile devices.
Similar to this - standing in first person and pointing your mouse at something:
If you mean you want to raycast ony from the center of the screen, then you can make use of Camera:ViewportPointToRay():
local Camera = workspace.CurrentCamera
local rayLength = 100 --> the length of the raycast
local middle = Camera.ViewportSize / 2 --> the middle of the viewport
local unitRay = Camera:ViewportPointToRay(middle.X, middle.Y)
local hit = workspace:Raycast(
unitRay.Origin, --> casting from the middle of the screen
unitRay.Direction * rayLength --> extruding forward from the middle of the screen
)
if hit then
print("Something was hit!")
end
First, let’s make a RaycastParams object so the cast doesn’t hit the player.
local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local params = RaycastParams.new()
params.FilterDescendantsInstances = {char}
params.FilterType = Enum.RaycastFilterType.Exclude -- ignore anything in the FilterDescendantsInstances
Now, we need to make a function to do it.
local middle = Vector2.new(0, 0)
local function cast()
--convert location to ray
local ray = workspace.CurrentCamera:ScreenPointToRay(middle.X, middle.Y)
--cast the ray with the params so we avoid character hits
local hit = workspace:Raycast(ray.Origin, ray.Direction * 30, --[[length]] params)
if hit then
--the ray intersected a part. Let's output the part and its material.
print(hit.Instance, "was hit by the ray. Material is ", hit.Material)
end
end
Now, just cast it whenever. I’ll do it every frame for an example.
local rs = game:GetService("RunService")
rs:BindToRenderStep("Cast", 2000, cast)