I have a script that detects if a player touches a part in the map and plays audio based on what part it was. I am doing this by using .Touched events, but it can be difficult sometimes to create a part that fits around the area. I would like to know if there is an easier way or more efficient way (better performance) or if using .Touched is the best way to do this.
These are what the areas look like. There are many gaps as the player could go back and forth, which would mess up the sound. However, it also means the music could be incorrect if they managed to not touch any other parts, and I am not sure how I could get around this issue
The most efficient way to detect if a player is in a part is to use Workspace:GetPartsInPart(). It works geometrically and returns a simple list of every part that is touching a part. This uses RaycastingParams as one of it’s parameters, so you can easily filter many unnecessary parts as well.
local Zone = require(game:GetService("ReplicatedStorage").Zone)
local container = workspace.YourModel
local zone1 = Zone.new(container)
zone1.playerEntered:Connect(function(player)
-- do something
end)
zone1.playerExited:Connect(function(player)
-- do something
end)
This won’t work for my situation as :GetPartsInPart needs the objects touching to have CanCollide/CanQuery on, but the areas have this disabled (they only have CanTouch enabled). Thanks for trying to help though!
The module script doesn’t seem to work for me, but I also prefer to write my own code rather than just get a working version online. I would just like to know if .Touched is the best way and how to fix the ‘gaps’ between the areas, but thanks for trying to help!
Why doesn’t it work, did you get any errors? It’s way more reliable and easier to use rather than .Touched. I’m using it for my game and it works perfectly there.
Your best bet would be to use raycasting. So your workflow would be something like this → player starts walking → start raycasting from the rootpart downwards → if it hits a region part → play that regions music → if it hits nothing then do nothing