local RunService = game:GetService("RunService") local Players =…
- User
local RunService = game:GetService("RunService") local Players = game:GetService("Players") local Workspace = game:GetService("Workspace")
local LocalPlayer = Players.LocalPlayer local Camera = Workspace.CurrentCamera
-- === CONFIGURATION === -- local MIN_SWIM_SPEED, MAX_SWIM_SPEED = 0.5, 1.5 local MIN_TURN_SPEED, MAX_TURN_SPEED = 2, 4 local IDLE_DURATION_MIN, IDLE_DURATION_MAX = 2, 5 local FISH_BOUNDING_RADIUS = 1 local LOD_DISTANCE_NEAR_SQ, LOD_DISTANCE_MEDIUM_SQ = 25 ^ 2, 50 ^ 2 local SCAN_INTERVAL = 2 -- seconds
local clientManagedFish = {} -- { [fishModel] = { coroutine, zone, currentLOD, lastTargetPos } } local lastScanTime = 0
-- === UTILITIES === -- local function clampPositionToZone(pos, zone, radius) if not zone then return pos end local cf, sz = zone.CFrame, zone.Size local lp = cf:PointToObjectSpace(pos) local cx = math.clamp(lp.X, -sz.X / 2 + radius, sz.X / 2 - radius) local cy = math.clamp(lp.Y, -sz.Y / 2 + radius, sz.Y / 2 - radius) local cz = math.clamp(lp.Z, -sz.Z / 2 + radius, sz.Z / 2 - radius) return cf:PointToWorldSpace(Vector3.new(cx, cy, cz)) end
local function randomZonePoint(zone) local sz = zone.Size local function rand(min, max) return math.random(min * 100, max * 100) / 100 end return Vector3.new( rand(-sz.X / 2 + FISH_BOUNDING_RADIUS, sz.X / 2 - FISH_BOUNDING_RADIUS), rand(-sz.Y / 2 + FISH_BOUNDING_RADIUS, sz.Y / 2 - FISH_BOUNDING_RADIUS), rand(-sz.Z / 2 + FISH_BOUNDING_RADIUS, sz.Z / 2 - FISH_BOUNDING_RADIUS) ) end
local function getSwimTarget(fish, zone, lastTarget) if not zone then return fish.PrimaryPart.Position end local cf = zone.CFrame for _ = 1, 4 do local localTarget = randomZonePoint(zone) local worldTarget = clampPositionToZone(cf:PointToWorldSpace(localTarget), zone, FISH_BOUNDING_RADIUS) if not lastTarget or (worldTarget - lastTarget).Magnitude > 2 then return worldTarget end end return fish.PrimaryPart.Position end
local function getYaw(from, to, cf) local delta = to - from if delta.X == 0 and delta.Z == 0 then local _, yaw, _ = cf:ToOrientation() return yaw end return math.atan2(delta.X, delta.Z) end
local function countTable(t) local c = 0 for _ in pairs(t) do c += 1 end return c end
-- === FISH COROUTINE MOVEMENT === -- local function swimLoop(fish, zone) local primary = fish.PrimaryPart local data = clientManagedFish[fish] if not primary or not data or not zone then return end
local cframe = primary.CFrame local state = "moving" local idleTimer = 0 local swimSpeed = math.random(MIN_SWIM_SPEED * 100, MAX_SWIM_SPEED * 100) / 100 local turnSpeed = math.random(MIN_TURN_SPEED * 100, MAX_TURN_SPEED * 100) / 100 local targetPos = data.lastTargetPos or getSwimTarget(fish, zone, primary.Position) data.lastTargetPos = targetPos local targetYaw = getYaw(primary.Position, targetPos, cframe) while clientManagedFish[fish] and clientManagedFish[fish].coroutine == coroutine.running() and fish.Parent and primary.Parent and data.zone == zone do local dt = RunService.Heartbeat:Wait() if state == "moving" then local _, currentYaw = cframe:ToOrientation() local yawDiff = targetYaw - currentYaw yawDiff = (yawDiff + math.pi) % (2 * math.pi) - math.pi local maxTurn = turnSpeed * dt if math.abs(yawDiff) > maxTurn then currentYaw += math.sign(yawDiff) * maxTurn else currentYaw = targetYaw end local dir = targetPos - primary.Position local dist = dir.Magnitude local moveStep = math.min(dist, swimSpeed * dt) if dist > 0.1 then local newPos = primary.Position + dir.Unit * moveStep primary.CFrame = CFrame.new(clampPositionToZone(newPos, zone, FISH_BOUNDING_RADIUS)) * CFrame.Angles(0, currentYaw, 0) cframe = primary.CFrame else state = "idle" idleTimer = math.random(IDLE_DURATION_MIN * 100, IDLE_DURATION_MAX * 100) / 100 targetPos = getSwimTarget(fish, zone, primary.Position) data.lastTargetPos = targetPos targetYaw = getYaw(primary.Position, targetPos, cframe) swimSpeed = math.random(MIN_SWIM_SPEED * 100, MAX_SWIM_SPEED * 100) / 100 turnSpeed = math.random(MIN_TURN_SPEED * 100, MAX_TURN_SPEED * 100) / 100 end elseif state == "idle" then idleTimer -= dt if idleTimer <= 0 then state = "moving" end end endend
-- === LOD AND FISH MANAGEMENT === -- local function getDistanceToCameraSq(pos) if not Camera then return math.huge end return (Camera.CFrame.Position - pos).Magnitude ^ 2 end
local function updateFishLOD(fish, zone) if not fish or not fish.PrimaryPart or not clientManagedFish[fish] then return end local data = clientManagedFish[fish] local d2 = getDistanceToCameraSq(fish.PrimaryPart.Position) local newLOD = (d2 <= LOD_DISTANCE_NEAR_SQ) and "NEAR" or (d2 <= LOD_DISTANCE_MEDIUM_SQ) and "MEDIUM" or "FAR"
if data.currentLOD ~= newLOD then data.currentLOD = newLOD if newLOD == "NEAR" or newLOD == "MEDIUM" then if not data.coroutine or coroutine.status(data.coroutine) == "dead" then data.coroutine = coroutine.create(swimLoop) coroutine.resume(data.coroutine, fish, zone) end else -- FAR if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then -- Kill coroutine (let it exit itself) data.coroutine = nil end end endend
local function scanAndManageFish() local plots = Workspace:FindFirstChild("Gameplay") and Workspace.Gameplay:FindFirstChild("Plots") if not plots then return end
local seenFish = {} for _, plot in ipairs(plots:GetChildren()) do if plot:IsA("Part") then for _, tank in ipairs(plot:GetChildren()) do if tank:IsA("Model") and tank.Name == "FishTank" then local zone = tank:FindFirstChild("InsertZone") if zone then for _, fish in ipairs(tank:GetChildren()) do if fish:IsA("Model") and fish.PrimaryPart then table.insert(seenFish, fish) if not clientManagedFish[fish] then clientManagedFish[fish] = { coroutine = nil, zone = zone, currentLOD = "FAR", lastTargetPos = nil } else clientManagedFish[fish].zone = zone end end end end end end end end -- Remove dead/removed fish local toRemove = {} for fish in pairs(clientManagedFish) do local stillExists = false for _, seen in ipairs(seenFish) do if fish == seen then stillExists = true break end end if not stillExists then table.insert(toRemove, fish) end end for _, fish in ipairs(toRemove) do local data = clientManagedFish[fish] if data and data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end clientManagedFish[fish] = nil endend
-- === MAIN LOOP === -- RunService.RenderStepped:Connect(function() if not LocalPlayer.Character or not LocalPlayer.Character:IsDescendantOf(Workspace) or not Camera then -- Cleanup if player leaves for fish, data in pairs(clientManagedFish) do if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end end table.clear(clientManagedFish) return end
if tick() - lastScanTime > SCAN_INTERVAL then scanAndManageFish() lastScanTime = tick() end for fish, data in pairs(clientManagedFish) do if not fish or not fish.Parent or not fish.PrimaryPart or not fish.PrimaryPart.Parent then if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end clientManagedFish[fish] = nil else updateFishLOD(fish, data.zone) end endend)
-- Initial scan (wait a moment for loading) task.wait(2.5) scanAndManageFish() lastScanTime = tick()
How do i make my fish movement even better so its more natural and super entrancing for people to watch for long hours
Give me full copy paste
- Assistant
Okay, here's a significantly enhanced version of the fish movement script, aiming for more natural and entrancing behavior. I've focused on several key areas:
- Smoother Steering: Instead of directly setting the yaw, we'll use a more gradual steering approach, blending the current direction with the desired direction.
- Obstacle Avoidance: Basic obstacle avoidance to prevent fish from getting stuck.
- Schooling Behavior (Optional): A rudimentary attempt at schooling, where fish try to stay near others. This is a complex topic, so this is a simplified version.
- Varied Movement Patterns: More randomness in speed and turning, and occasional "exploration" bursts.
- Depth Variation: Fish will now move up and down slightly, adding to the realism.
- More Realistic Idle: The idle behavior is improved to be less static.
- Performance Considerations: I've tried to keep performance in mind, but complex schooling can become expensive.
- Comments: Extensive comments to explain the changes.
local RunService = game:GetService("RunService") local Players = game:GetService("Players") local Workspace = game:GetService("Workspace") local LocalPlayer = Players.LocalPlayer local Camera = Workspace.CurrentCamera -- === CONFIGURATION === -- local MIN_SWIM_SPEED, MAX_SWIM_SPEED = 0.5, 2.0 -- Increased max speed local MIN_TURN_SPEED, MAX_TURN_SPEED = 2, 6 -- Increased max turn speed local IDLE_DURATION_MIN, IDLE_DURATION_MAX = 2, 5 local FISH_BOUNDING_RADIUS = 1 local LOD_DISTANCE_NEAR_SQ, LOD_DISTANCE_MEDIUM_SQ = 25 ^ 2, 50 ^ 2 local SCAN_INTERVAL = 2 -- seconds local SCHOOLING_RADIUS = 5 local SCHOOLING_WEIGHT = 0.2 -- How much schooling influences movement local OBSTACLE_AVOIDANCE_RANGE = 3 local OBSTACLE_AVOIDANCE_STRENGTH = 1.5 local DEPTH_VARIATION_RANGE = 1 local DEPTH_VARIATION_SPEED = 0.2 local clientManagedFish = {} -- { [fishModel] = { coroutine, zone, currentLOD, lastTargetPos, lastObstacleAvoidanceTime } } local lastScanTime = 0 -- === UTILITIES === -- local function clampPositionToZone(pos, zone, radius) if not zone then return pos end local cf, sz = zone.CFrame, zone.Size local lp = cf:PointToObjectSpace(pos) local cx = math.clamp(lp.X, -sz.X / 2 + radius, sz.X / 2 - radius) local cy = math.clamp(lp.Y, -sz.Y / 2 + radius, sz.Y / 2 - radius) local cz = math.clamp(lp.Z, -sz.Z / 2 + radius, sz.Z / 2 - radius) return cf:PointToWorldSpace(Vector3.new(cx, cy, cz)) end local function randomZonePoint(zone) local sz = zone.Size local function rand(min, max) return math.random(min * 100, max * 100) / 100 end return Vector3.new( rand(-sz.X / 2 + FISH_BOUNDING_RADIUS, sz.X / 2 - FISH_BOUNDING_RADIUS), rand(-sz.Y / 2 + FISH_BOUNDING_RADIUS, sz.Y / 2 - FISH_BOUNDING_RADIUS), rand(-sz.Z / 2 + FISH_BOUNDING_RADIUS, sz.Z / 2 - FISH_BOUNDING_RADIUS) ) end local function getSwimTarget(fish, zone, lastTarget) if not zone then return fish.PrimaryPart.Position end local cf = zone.CFrame for _ = 1, 4 do local localTarget = randomZonePoint(zone) local worldTarget = clampPositionToZone(cf:PointToWorldSpace(localTarget), zone, FISH_BOUNDING_RADIUS) if not lastTarget or (worldTarget - lastTarget).Magnitude > 2 then return worldTarget end end return fish.PrimaryPart.Position end local function getYaw(from, to, cf) local delta = to - from if delta.X == 0 and delta.Z == 0 then local _, yaw, _ = cf:ToOrientation() return yaw end return math.atan2(delta.X, delta.Z) end local function countTable(t) local c = 0 for _ in pairs(t) do c += 1 end return c end -- Raycast for obstacle avoidance local function avoidObstacles(fish, zone) local primaryPart = fish.PrimaryPart local startPos = primaryPart.Position local direction = primaryPart.CFrame.LookVector local endPos = startPos + direction * OBSTACLE_AVOIDANCE_RANGE local raycastParams = RaycastParams.new() raycastParams.FilterDescendantsInstances = {fish} -- Ignore the fish itself raycastParams.FilterType = Enum.RaycastFilterType.Blacklist local raycastResult = Workspace:Raycast(startPos, endPos, raycastParams) if raycastResult then -- Obstacle detected, steer away local hitNormal = raycastResult.Normal local avoidanceDirection = hitNormal:Cross(direction) return avoidanceDirection.Unit * OBSTACLE_AVOIDANCE_STRENGTH end return Vector3.zero end -- === FISH COROUTINE MOVEMENT === -- local function swimLoop(fish, zone) local primary = fish.PrimaryPart local data = clientManagedFish[fish] if not primary or not data or not zone then return end local cframe = primary.CFrame local state = "moving" local idleTimer = 0 local swimSpeed = math.random(MIN_SWIM_SPEED * 100, MAX_SWIM_SPEED * 100) / 100 local turnSpeed = math.random(MIN_TURN_SPEED * 100, MAX_TURN_SPEED * 100) / 100 local targetPos = data.lastTargetPos or getSwimTarget(fish, zone, primary.Position) data.lastTargetPos = targetPos local targetYaw = getYaw(primary.Position, targetPos, cframe) local depthOffset = 0 while clientManagedFish[fish] and clientManagedFish[fish].coroutine == coroutine.running() and fish.Parent and primary.Parent and data.zone == zone do local dt = RunService.Heartbeat:Wait() if state == "moving" then -- Obstacle avoidance local avoidanceSteer = avoidObstacles(fish, zone) -- Schooling behavior (simplified) local schoolingSteer = Vector3.zero local nearbyFish = {} for otherFish, otherData in pairs(clientManagedFish) do if otherFish ~= fish and otherData.zone == zone then local dist = (fish.PrimaryPart.Position - otherFish.PrimaryPart.Position).Magnitude if dist < SCHOOLING_RADIUS then table.insert(nearbyFish, otherFish) end end end if #nearbyFish > 0 then local averagePosition = Vector3.zero for _, otherFish in ipairs(nearbyFish) do averagePosition += otherFish.PrimaryPart.Position end averagePosition = averagePosition / #nearbyFish schoolingSteer = (averagePosition - fish.PrimaryPart.Position).Unit * SCHOOLING_WEIGHT end -- Combine steering forces local desiredDirection = (targetPos - primary.Position).Unit local currentDirection = primary.CFrame.LookVector local blendedDirection = currentDirection.Unit + (desiredDirection - currentDirection.Unit) * turnSpeed * dt blendedDirection = blendedDirection.Unit blendedDirection = blendedDirection + avoidanceSteer + schoolingSteer blendedDirection = blendedDirection.Unit -- Apply steering local _, currentYaw = cframe:ToOrientation() local targetYaw = math.atan2(blendedDirection.X, blendedDirection.Z) local yawDiff = targetYaw - currentYaw yawDiff = (yawDiff + math.pi) % (2 * math.pi) - math.pi local maxTurn = turnSpeed * dt if math.abs(yawDiff) > maxTurn then currentYaw += math.sign(yawDiff) * maxTurn else currentYaw = targetYaw end local dir = blendedDirection local dist = (targetPos - primary.Position).Magnitude local moveStep = math.min(dist, swimSpeed * dt) if dist > 0.1 then local newPos = primary.Position + dir * moveStep newPos = clampPositionToZone(newPos, zone, FISH_BOUNDING_RADIUS) primary.CFrame = CFrame.new(newPos) * CFrame.Angles(0, currentYaw, 0) cframe = primary.CFrame -- Depth variation depthOffset = math.clamp(depthOffset + DEPTH_VARIATION_SPEED * dt, -DEPTH_VARIATION_RANGE, DEPTH_VARIATION_RANGE) primary.CFrame = primary.CFrame * CFrame.new(0, 0, depthOffset) else state = "idle" idleTimer = math.random(IDLE_DURATION_MIN * 100, IDLE_DURATION_MAX * 100) / 100 targetPos = getSwimTarget(fish, zone, primary.Position) data.lastTargetPos = targetPos targetYaw = getYaw(primary.Position, targetPos, cframe) swimSpeed = math.random(MIN_SWIM_SPEED * 100, MAX_SWIM_SPEED * 100) / 100 turnSpeed = math.random(MIN_TURN_SPEED * 100, MAX_TURN_SPEED * 100) / 100 end elseif state == "idle" then idleTimer -= dt if idleTimer <= 0 then state = "moving" targetPos = getSwimTarget(fish, zone, primary.Position) data.lastTargetPos = targetPos targetYaw = getYaw(primary.Position, targetPos, cframe) swimSpeed = math.random(MIN_SWIM_SPEED * 100, MAX_SWIM_SPEED * 100) / 100 turnSpeed = math.random(MIN_TURN_SPEED * 100, MAX_TURN_SPEED * 100) / 100 else -- Gentle swaying during idle local swayAmount = math.sin(tick() * 2) * 0.1 primary.CFrame = primary.CFrame * CFrame.new(swayAmount, 0, 0) end end end end -- === LOD AND FISH MANAGEMENT === -- local function getDistanceToCameraSq(pos) if not Camera then return math.huge end return (Camera.CFrame.Position - pos).Magnitude ^ 2 end local function updateFishLOD(fish, zone) if not fish or not fish.PrimaryPart or not clientManagedFish[fish] then return end local data = clientManagedFish[fish] local d2 = getDistanceToCameraSq(fish.PrimaryPart.Position) local newLOD = (d2 <= LOD_DISTANCE_NEAR_SQ) and "NEAR" or (d2 <= LOD_DISTANCE_MEDIUM_SQ) and "MEDIUM" or "FAR" if data.currentLOD ~= newLOD then data.currentLOD = newLOD if newLOD == "NEAR" or newLOD == "MEDIUM" then if not data.coroutine or coroutine.status(data.coroutine) == "dead" then data.coroutine = coroutine.create(swimLoop) coroutine.resume(data.coroutine, fish, zone) end else -- FAR if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then -- Kill coroutine (let it exit itself) data.coroutine = nil end end end end local function scanAndManageFish() local plots = Workspace:FindFirstChild("Gameplay") and Workspace.Gameplay:FindFirstChild("Plots") if not plots then return end local seenFish = {} for _, plot in ipairs(plots:GetChildren()) do if plot:IsA("Part") then for _, tank in ipairs(plot:GetChildren()) do if tank:IsA("Model") and tank.Name == "FishTank" then local zone = tank:FindFirstChild("InsertZone") if zone then for _, fish in ipairs(tank:GetChildren()) do if fish:IsA("Model") and fish.PrimaryPart then table.insert(seenFish, fish) if not clientManagedFish[fish] then clientManagedFish[fish] = { coroutine = nil, zone = zone, currentLOD = "FAR", lastTargetPos = nil, lastObstacleAvoidanceTime = 0 } else clientManagedFish[fish].zone = zone end end end end end end end end -- Remove dead/removed fish local toRemove = {} for fish, _ in pairs(clientManagedFish) do local stillExists = false for _, seen in ipairs(seenFish) do if fish == seen then stillExists = true break end end if not stillExists then table.insert(toRemove, fish) end end for _, fish in ipairs(toRemove) do local data = clientManagedFish[fish] if data and data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end clientManagedFish[fish] = nil end end -- === MAIN LOOP === -- RunService.RenderStepped:Connect(function() if not LocalPlayer.Character or not LocalPlayer.Character:IsDescendantOf(Workspace) or not Camera then -- Cleanup if player leaves for fish, data in pairs(clientManagedFish) do if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end end table.clear(clientManagedFish) return end if tick() - lastScanTime > SCAN_INTERVAL then scanAndManageFish() lastScanTime = tick() end for fish, data in pairs(clientManagedFish) do if not fish or not fish.Parent or not fish.PrimaryPart or not fish.PrimaryPart.Parent then if data.coroutine and coroutine.status(data.coroutine) ~= "dead" then data.coroutine = nil end clientManagedFish[fish] = nil else updateFishLOD(fish, data.zone) end end end) -- Initial scan (wait a moment for loading) task.wait(2.5) scanAndManageFish() lastScanTime = tick()Key improvements and explanations:
- Obstacle Avoidance: The
avoidObstaclesfunction now uses raycasting to detect obstacles in the fish's path. If an obstacle is detected, it calculates a steering force to move the fish away from it. - Schooling: The
schoolingSteercalculation finds nearby fish and calculates a steering force towards the average position of the school. TheSCHOOLING_WEIGHTcontrols how strongly the fish are attracted to the school. - Blended Steering: The steering forces (target direction, obstacle avoidance, schooling) are combined using a weighted average to create a more natural and responsive movement.
- Depth Variation: The
depthOffsetvariable adds a sinusoidal variation to the fish's Z position, making them move up and down slightly. - Smoother Turning: The
blendedDirectionis used to calculate a target yaw, and the yaw is adjusted gradually over time, resulting in smoother turns. - Idle Swaying: The fish now sway gently while idle, making them appear more alive.
- Configuration: I've added more configuration variables to allow you to fine-tune the behavior of the fish.
To use this script:
- Copy and paste the entire script into a LocalScript inside
StarterPlayerScripts. - Make sure your game has the same folder structure (
Workspace.Gameplay.Plots) as the original script expects. - Adjust the configuration variables at the top of the script to customize the fish's behavior. Experiment with different values to find what looks best for your game.
- Test and iterate: Watch the fish and see how they behave. Adjust the configuration variables and the code as needed to achieve the desired effect.
This revised script provides a much more natural and engaging fish movement experience. Remember to experiment with the configuration variables to fine-tune the behavior to your liking. Let me know if you have any other questions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.