Help with Terrain raycasting with mouse

How do I whenever i click on terrain its knows for example that its grass terrain so my player herbivore can eat the terrain grass whenever they click on the grass terrain

2 Likes

Try this article, it might help.

You could cast a ray cast from below the player to see what place they are In .(I don’t really think using a ray cast from the mouse would be viable because I think you just want whatever your making to only eat what’s next to it)

And to detect what material it is, I believe that you can just check what material the ray cast hits and if it is terrain material then you do whatever you want

thats better than my concept thank you

local Enumeration = Enum
local Game = game
local Workspace = workspace
local UserInputService = Game:GetService("UserInputService")
local Camera = Workspace.CurrentCamera

local function OnInputBegan(InputObject, GameProcessed)
	if GameProcessed then return end
	if InputObject.UserInputType ~= Enumeration.UserInputType.MouseButton1 then return end
	local Ray = Camera:ScreenPointToRay(InputObject.Position.X, InputObject.Position.Y)
	local Result = Workspace:Raycast(Ray.Origin, Ray.Direction * 250)
	if not Result then return end
	if Result.Instance:IsA("Terrain") then print(Result.Material.Name) end
end

UserInputService.InputBegan:Connect(OnInputBegan)

https://developer.roblox.com/en-us/api-reference/datatype/RaycastParams
You can pass a ‘RaycastParams’ object as the third argument to Raycast() if necessary.

Decrease ‘250’ if you want to reduce the mouse’s range from the character.

IVE solved its thank you all who helped me Here is my code if your wondering

–Localscript:
local UIS = game:GetService(“UserInputService”)
local rep = game.ReplicatedStorage
local Herbivores = rep:WaitForChild(“Herbivores”) --Herbivores is a folder in replicatedstorage which contains Remoteevent called grasseaters so you will have to add those yourself which is simple

-- A sample function providing one usage of InputBegan

UIS.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
print(“button is down”)

	Herbivores.grasseaters:FireServer()
end

end)

–Script:
local rep = game.ReplicatedStorage
local Herbivores = rep:WaitForChild(“Herbivores”) --Herbivores is a folder in replicatedstorage which contains Remoteevent called grasseaters so you will have to add those yourself which is simple

Herbivores.grasseaters.OnServerEvent:Connect(function(player)
local char = player.Character
local part = char.LowerTorso – path to rod
local ray = Ray.new(part.Position, Vector3.new(0, -10, 0))
local _, _, _, material = workspace:FindPartOnRayWithWhitelist(ray, {workspace.Terrain})
– part, position, ignorewater

print(material)

end)

thank you but i realized I shoudnt be using grass its wouldn’t be very realistic if their were grass far away and the player was eating the grass on rocks far awway