So im making a thing if player close to npc it will do something.
I used .Touching event and invisible part near npc to get it, but also i used .TouchEnded event and the problem is that .TouchEnded fires even if player not moving because idle animation is playing and players arm is moving out of npc and that cause .TouchEnded to fire. So is there way i can fix it or maybe there better ways to check?
Also there would be ALOT of npcs in game so if i use Region3 and use while loop to check if player near it might cause lags so i don’t know what should i do.
You could use this. If itt doesn’t work please reply, or ping me
local Player = game.Players.LocalPlayer
local RunService = game:GetService("RunService")
local Distance = 5
RunService.RenderStepped:Connect(function()
if Player:DistanceFromCharacter(location of the npc in the workspace) < Distance then
-- Code here
else
-- Code here
end
end)
Hey so if I assume correctly that it is related to finding nearest NPC for the sake of allowing interaction, there is many ways to do it.
Don’t assume a while loop will lag until you try it. The most common way to do it is just to use a RunService event then connect a function that will constantly check the player’s distance from every other NPCs.
You could probably optimize with octrees or quadtrees. I am not sure how good Region3 is in this case because I feel like it’d be an expensive operation to do extremely quickly but if it isn’t, it’d be powerful as it locates only the space around the player to find NPCs rather than cycling through every NPC.
I have been thinking the same thing for a while now. I’ve always been taught in programming to only use code when it needs to be used and to not leave loops constantly running. I mean, imagine a game where you need to go through every mob’s position and every player’s position and compare every mob’s position to every player’s position. That would probably require some sort of an infinite loop that has inside it a nested for loop.
So, instead, I thought about this strategy, which may not be as taxing on the performance of your game. What if you set certain zones in your game, and once the player has entered a zone, you would check for the distance between that player and the mobs in that zone. This would be especially good for MMORPGs with multiple mobs and zones. Anyway, you could accomplish this using either a simple Region3, magnitude between the centre of the zone and the players, a convex hull if the zone is not that complicated. However, I am recently working on using a Concave Hull algorithm to achieve this so that I can simply use a set of nodes and use those nodes as boundary points. Once I am able to do this, I can simulate multiple things such as Delaunay triangulation, NPC movements and behaviour, collisions, etc.
Anyway, if I figure out how to do this I will edit this post and give you an answer then. For now, this is simply an idea and I am sure that others have made this before.
Good luck!