Help with raycasting pet to the floor

I would like to raycast the pet to the floor because the pet currently just floats.

I looked at other posts but couldn’t figure it out so if anyone could help that would be amazing!

this is my current script

local runService = game:GetService("RunService")
local PetsModule = require(game.ReplicatedStorage.ModuleScript)
local character = game.Players.LocalPlayer.Character
local rootPart = character.HumanoidRootPart
local pets = {}
local spacing = 4

runService.Heartbeat:Connect(function(deltaTime)
	local columns = math.floor(math.sqrt(#pets))
	local offset = Vector3.new(-columns / 2 * spacing + spacing / 2, 0, 4) 
	for i, pet in pets do
		i -= 1
		local x = i % columns
		local z = math.floor(i / columns)
		pet.CFrame = pet.CFrame:Lerp(rootPart.CFrame * CFrame.new(offset + Vector3.new(x, -0.45, z) * spacing), 0.1)
		if character.Humanoid.MoveDirection.Magnitude > 0 then
			-- walking animation
			pet.CFrame = pet.CFrame:Lerp(pet.CFrame *CFrame.fromEulerAnglesXYZ(math.cos(7 * time() + 1)/2,0,0),0.1)
		end
	end
end)

game.ReplicatedStorage.CreatePet.OnClientEvent:Connect(function(plr, d)
	local Pet = PetsModule:AddPet("Dog")
	table.insert(pets, Pet)
end)
1 Like

If you’d like to learn raycasting, you should check this tutorial by Roblox. Raycasting can be implemented in your game using the function workspace:Raycast() which I will tell you how to use:

  1. The first parameter of workspace:Raycast() is the Vector3 position in which the ray is going to start, in your case, it’s the pet’s position.
  2. The second parameter is going to represent the direction it’s going to be. Watch out! This parameter isn’t a position! This parameter is added by Roblox and will determine the second point in your ray cast. In your case, it’ll be Vector3.new(0,-{PetSizeY or any number}, 0).
  3. Use RaycastParams in order to tell the game which instances you want to filter, whether you want to ignore water, ignore CanCollide, etc…

After running this function, Roblox will return a RaycastResult. If Roblox didn’t detect any parts/terrain it won’t return this and instead Roblox will return nil, so it’s in handy to have the following to avoid placing the pet on nothing:

local RaycastResult = workspace:Raycast(pet.Position, Vector3.new(0,-6,0), RaycastParams)
if not RaycastResult then return end

RaycastResults have different properties. For instance:

  1. Instance (the part which it touched)
  2. Position (Vector3 in which it touched)
  3. etc

We’re going to only focus on the Instance property, so you can get the part that it touched. Now, by following this post on the developer forum, you can find a way to place a part on top of another one; this part will be your pet:

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