Untitled conversation
- User
if CLIENT then ------------------------------------------------------------------- -- FirstPersonView Module -- Provides a precise first-person camera positioned at the player's head. ------------------------------------------------------------------- -- Define the FirstPersonView table local FirstPersonView = { -- Configuration table with default values. These can be overridden via -- console variables (ConVars) for dynamic configuration. config = { headBoneNames = { "ValveBiped.Bip01_Head1", -- Priority-ordered list of head bone names "ValveBiped.Bip01_Neck1", "ValveBiped.Bip01_EyeLeft", "ValveBiped.Bip01_EyeRight", "ValveBiped.Bip01_Mouth" }, cameraOffset = Vector(0, 0, 0), -- Default camera offset (modifiable via ConVar) drawLocalPlayer = true, -- Whether to draw the local player model in first-person spectatorTeam = nil, -- Spectator team identifier (to be set during initialization) notifyOnError = true, -- Whether to notify the player on errors cameraCollision = true, -- Whether to enable camera collision detection maxCameraDistance = 60, -- Maximum camera distance to prevent clipping }, -- Table to cache head bone indices for the local player headBoneIndices = {}, -- Flag to ensure single initialization initialized = false, -- Rate limiter for error notifications to prevent spam errorRateLimiter = { lastErrorTime = 0, cooldown = 5, -- seconds }, } --------------------------------------------------- -- Utility Functions --------------------------------------------------- -- Utility function to log messages with a prefix local function Log(message, isError) if isError then if FirstPersonView.config.notifyOnError then chat.AddText(Color(255, 0, 0), "[FirstPersonView] " .. message) end print("[FirstPersonView] " .. message) else print("[FirstPersonView] " .. message) end end -- Utility function to check and update the rate limiter local function CanNotifyError() local currentTime = CurTime() if currentTime - FirstPersonView.errorRateLimiter.lastErrorTime >= FirstPersonView.errorRateLimiter.cooldown then FirstPersonView.errorRateLimiter.lastErrorTime = currentTime return true end return false end --------------------------------------------------- -- Configuration Loading and Management --------------------------------------------------- -- Function to load and apply camera offset from ConVar local function LoadCameraOffset() local offsetX = GetConVar("fvp_camera_offset_x"):GetFloat() local offsetY = GetConVar("fvp_camera_offset_y"):GetFloat() local offsetZ = GetConVar("fvp_camera_offset_z"):GetFloat() FirstPersonView.config.cameraOffset = Vector(offsetX, offsetY, offsetZ) end -- Function to load head bone names from ConVar (comma-separated) local function LoadHeadBoneNames() local boneNamesString = GetConVar("fvp_head_bone_names"):GetString() local boneNamesRaw = string.Split(boneNamesString, ",") -- Trim whitespace and ensure uniqueness using a temporary table local uniqueBoneSet = {} local uniqueBoneList = {} for _, name in ipairs(boneNamesRaw) do local trimmed = string.Trim(name) if trimmed ~= "" and not uniqueBoneSet[trimmed] then table.insert(uniqueBoneList, trimmed) uniqueBoneSet[trimmed] = true end end FirstPersonView.config.headBoneNames = uniqueBoneList end -- Function to load spectator team from ConVar local function LoadSpectatorTeam() -- Attempt to fetch TEAM_SPECTATOR safely local spectatorTeam = GetConVar("fvp_spectator_team"):GetInt() if spectatorTeam <= 0 then -- Fallback to default if invalid spectatorTeam = TEAM_SPECTATOR or 8 end FirstPersonView.config.spectatorTeam = spectatorTeam end -- Function to initialize ConVars for dynamic configuration local function InitializeConVars() CreateClientConVar("fvp_camera_offset_x", "0", true, false, "FirstPersonView: Camera offset X (forward/backward)") CreateClientConVar("fvp_camera_offset_y", "0", true, false, "FirstPersonView: Camera offset Y (left/right)") CreateClientConVar("fvp_camera_offset_z", "0", true, false, "FirstPersonView: Camera offset Z (up/down)") CreateClientConVar("fvp_head_bone_names", "ValveBiped.Bip01_Head1,ValveBiped.Bip01_Neck1,ValveBiped.Bip01_EyeLeft,ValveBiped.Bip01_EyeRight,ValveBiped.Bip01_Mouth", true, false, "FirstPersonView: Comma-separated list of head bone names") CreateClientConVar("fvp_spectator_team", tostring(TEAM_SPECTATOR or 8), true, false, "FirstPersonView: Spectator team identifier") end -- Function to refresh configuration from ConVars local function RefreshConfig() LoadCameraOffset() LoadHeadBoneNames() LoadSpectatorTeam() end -- Hook to watch for ConVar changes and refresh configuration accordingly local function SetupConVarChangeHooks() -- Camera Offset Changes cvars.AddChangeCallback("fvp_camera_offset_x", LoadCameraOffset, "FirstPersonView_CameraOffsetX") cvars.AddChangeCallback("fvp_camera_offset_y", LoadCameraOffset, "FirstPersonView_CameraOffsetY") cvars.AddChangeCallback("fvp_camera_offset_z", LoadCameraOffset, "FirstPersonView_CameraOffsetZ") -- Head Bone Names Change cvars.AddChangeCallback("fvp_head_bone_names", LoadHeadBoneNames, "FirstPersonView_HeadBoneNames") -- Spectator Team Change cvars.AddChangeCallback("fvp_spectator_team", LoadSpectatorTeam, "FirstPersonView_SpectatorTeam") end --------------------------------------------------- -- Bone Caching --------------------------------------------------- -- Function to cache head bone indices for the local player function FirstPersonView:CacheHeadBones() local ply = LocalPlayer() if not IsValid(ply) then if CanNotifyError() then Log("Local player is not valid. Cannot cache head bones.", true) end return end local model = ply:GetModel() if not model or model == "" then if CanNotifyError() then Log("Local player's model is invalid. Cannot cache head bones.", true) end return end -- Clear existing cached bones table.Empty(self.headBoneIndices) -- Iterate through the list of possible head bone names and cache all found bones for _, boneName in ipairs(self.config.headBoneNames) do local boneIndex = ply:LookupBone(boneName) if boneIndex then table.insert(self.headBoneIndices, boneIndex) -- Optional: Uncomment the following line to reduce console spam -- Log("Cached head bone '" .. boneName .. "' (Index: " .. tostring(boneIndex) .. ") for model '" .. model .. "'.", false) end end -- If no head bones found, log warning with rate limiting if #self.headBoneIndices == 0 and CanNotifyError() then Log("Warning: No valid head bones found for model '" .. model .. "'. Expected bones: " .. table.concat(self.config.headBoneNames, ", "), true) end end --------------------------------------------------- -- Camera Positioning --------------------------------------------------- -- Function to get the head position for the local player function FirstPersonView:GetHeadPosition() local ply = LocalPlayer() if not IsValid(ply) then return nil end if #self.headBoneIndices == 0 then -- Attempt to cache head bones if not already cached self:CacheHeadBones() if #self.headBoneIndices == 0 then -- Fallback to eye position if head bones not found Log("Using eye position as fallback for camera.", true) return ply:EyePos() end end -- Use the first valid head bone position local boneIndex = self.headBoneIndices[1] local bonePos = ply:GetBonePosition(boneIndex) if bonePos then return bonePos else Log("Failed to get position for head bone index " .. tostring(boneIndex) .. ". Using eye position.", true) return ply:EyePos() end end -- Variable to store the current view local currentView = { origin = Vector(0, 0, 0), angles = Angle(0, 0, 0), fov = 0, drawviewer = false, } -- Hook to calculate and set the camera view function FirstPersonView:CalcView(ply, pos, angles, fov) if not IsValid(ply) then return end if ply:Team() == self.config.spectatorTeam then return end local headPos = self:GetHeadPosition() if not headPos then return end -- Use the player's actual view angles to ensure camera aligns with player's view local playerAngles = ply:EyeAngles() -- Calculate the desired camera position based on the head position and camera offset local desiredCameraPos = headPos + playerAngles:Forward() * self.config.cameraOffset.x + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z -- Implement camera collision detection to prevent clipping if self.config.cameraCollision then local trace = {} trace.start = headPos trace.endpos = desiredCameraPos trace.filter = ply trace.mask = MASK_VISIBLE_AND_NPCS local tr = util.TraceLine(trace) if tr.Hit then local distance = tr.HitPos:Distance(headPos) if distance < self.config.maxCameraDistance then desiredCameraPos = tr.HitPos else -- Limit the camera distance desiredCameraPos = headPos + playerAngles:Forward() * self.config.maxCameraDistance + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z end end end -- Directly set the camera position and angles without smoothing currentView.origin = desiredCameraPos currentView.angles = playerAngles currentView.fov = fov currentView.drawviewer = self.config.drawLocalPlayer return currentView end --------------------------------------------------- -- Local Player Model Rendering --------------------------------------------------- -- Function to determine whether to draw the local player model function FirstPersonView:ShouldDrawLocalPlayer() local ply = LocalPlayer() if not IsValid(ply) then return true end -- Do not draw the player model if in spectator mode if ply:Team() == self.config.spectatorTeam then return false end return self.config.drawLocalPlayer end --------------------------------------------------- -- Bone Manipulation for Head Hiding --------------------------------------------------- -- Store original bone scales to restore after manipulation FirstPersonView.originalBoneScales = {} -- Function to hide the player's head bones function FirstPersonView:HideHeadBones() local ply = LocalPlayer() if not IsValid(ply) then return end if #self.headBoneIndices == 0 then return end for _, boneIndex in ipairs(self.headBoneIndices) do -- Store the original scale if not already stored if not self.originalBoneScales[boneIndex] then local originalScale = ply:GetManipulateBoneScale(boneIndex) if originalScale then self.originalBoneScales[boneIndex] = originalScale else self.originalBoneScales[boneIndex] = Vector(1, 1, 1) end end -- Hide the bone by setting its scale to zero ply:ManipulateBoneScale(boneIndex, Vector(0, 0, 0)) end end -- Function to restore the player's head bones function FirstPersonView:RestoreHeadBones() local ply = LocalPlayer() if not IsValid(ply) then return end if #self.headBoneIndices == 0 then return end for _, boneIndex in ipairs(self.headBoneIndices) do if self.originalBoneScales[boneIndex] then ply:ManipulateBoneScale(boneIndex, self.originalBoneScales[boneIndex]) self.originalBoneScales[boneIndex] = nil else -- If original scale wasn't stored, ensure it's visible ply:ManipulateBoneScale(boneIndex, Vector(1, 1, 1)) end end end -- Hook to handle pre-player draw function FirstPersonView:PrePlayerDraw(ply) if ply ~= LocalPlayer() then return end self:HideHeadBones() end -- Hook to handle post-player draw function FirstPersonView:PostPlayerDraw(ply) if ply ~= LocalPlayer() then return end self:RestoreHeadBones() end --------------------------------------------------- -- Event Handlers --------------------------------------------------- -- Hook to handle player model changes function FirstPersonView:OnPlayerSetModel(ply) if ply ~= LocalPlayer() then return end self:CacheHeadBones() end -- Hook to handle player spawn events function FirstPersonView:OnPlayerSpawn(ply) if ply ~= LocalPlayer() then return end -- Delay caching to ensure the model is fully loaded timer.Simple(0.5, function() if IsValid(ply) then self:CacheHeadBones() end end) end -- Hook to handle player disconnection and clean up cache function FirstPersonView:OnPlayerDisconnected(ply) if ply ~= LocalPlayer() then return end -- Clear cached bone indices and restore bone scales if necessary if #self.headBoneIndices > 0 then self:RestoreHeadBones() table.Empty(self.headBoneIndices) Log("Cleared cached head bones due to player disconnection.", false) end end --------------------------------------------------- -- Initialization and Cleanup --------------------------------------------------- -- Function to clean up all hooks and cached data function FirstPersonView:RemoveHooks() hook.Remove("CalcView", "FirstPersonView_CalcView") hook.Remove("ShouldDrawLocalPlayer", "FirstPersonView_ShouldDrawLocalPlayer") hook.Remove("PlayerSetModel", "FirstPersonView_PlayerSetModel") hook.Remove("PlayerSpawn", "FirstPersonView_PlayerSpawn") hook.Remove("PrePlayerDraw", "FirstPersonView_PrePlayerDraw") hook.Remove("PostPlayerDraw", "FirstPersonView_PostPlayerDraw") hook.Remove("ShutDown", "FirstPersonView_ShutDown") hook.Remove("PlayerDisconnected", "FirstPersonView_PlayerDisconnected") -- Restore bone scales if hidden self:RestoreHeadBones() -- Clear cached bone indices table.Empty(self.headBoneIndices) self.initialized = false Log("All hooks removed and caches cleared.", false) end -- Initialization function function FirstPersonView:Initialize() if self.initialized then Log("Initialization skipped: already initialized.", false) return end self.initialized = true InitializeConVars() RefreshConfig() SetupConVarChangeHooks() -- Cache head bones for the local player self:CacheHeadBones() -- Register hooks hook.Add("CalcView", "FirstPersonView_CalcView", function(ply, pos, angles, fov) return FirstPersonView:CalcView(ply, pos, angles, fov) end) hook.Add("ShouldDrawLocalPlayer", "FirstPersonView_ShouldDrawLocalPlayer", function() return FirstPersonView:ShouldDrawLocalPlayer() end) hook.Add("PlayerSetModel", "FirstPersonView_PlayerSetModel", function(ply) FirstPersonView:OnPlayerSetModel(ply) end) hook.Add("PlayerSpawn", "FirstPersonView_PlayerSpawn", function(ply) FirstPersonView:OnPlayerSpawn(ply) end) hook.Add("PrePlayerDraw", "FirstPersonView_PrePlayerDraw", function(ply) FirstPersonView:PrePlayerDraw(ply) end) hook.Add("PostPlayerDraw", "FirstPersonView_PostPlayerDraw", function(ply) FirstPersonView:PostPlayerDraw(ply) end) hook.Add("PlayerDisconnected", "FirstPersonView_PlayerDisconnected", function(ply) FirstPersonView:OnPlayerDisconnected(ply) end) hook.Add("ShutDown", "FirstPersonView_ShutDown", function() FirstPersonView:RemoveHooks() end) Log("FirstPersonView initialized successfully.", false) end --------------------------------------------------- -- Start Initialization if Not Already Initialized --------------------------------------------------- -- Prevent multiple instances by checking if already initialized if not FirstPersonView.initialized then -- Delay initialization to ensure teams and other dependencies are loaded hook.Add("InitPostEntity", "FirstPersonView_Initialize", function() FirstPersonView:Initialize() end) end ------------------------------------------------------------------- -- End of FirstPersonView Module ------------------------------------------------------------------- endБывает такое что камера проходит сквозь стены, исправь это
- Assistant
Проблема с прохождением камеры сквозь стены часто связана с настройкой трассировки коллизий. В вашем коде вы используете
util.TraceLineс маскойMASK_VISIBLE_AND_NPCS, которая может не охватывать все типы препятствий, такие как несущие стены или объекты с определёнными свойствами коллизий. Чтобы улучшить обнаружение коллизий и предотвратить прохождение камеры сквозь стены, рекомендуется внести следующие изменения:-
Измените Маску Коллизий:
Вместо
MASK_VISIBLE_AND_NPCSиспользуйтеMASK_SOLID, которая охватывает все твердые объекты, такие как стены и другие препятствия. Это обеспечит более надёжное обнаружение коллизий с несущими структурами. -
Используйте
util.TraceHullВместоutil.TraceLine:util.TraceHullпозволяет задать небольшие размеры "коробки" для трассировки, что помогает избежать ситуаций, когда тонкая линия пропускает препятствия или застревает модель камеры внутри стен. Это особенно полезно для предотвращения микро-проблем с коллизиями. -
Настройте Размеры
Hull:Установите небольшие размеры
Hull, чтобы трассировка была точной, но достаточно объемной для учёта возможных микроколлизий. -
Дополнительная Проверка и Логирование:
Добавьте логирование или отладочные сообщения, чтобы убедиться, что трассировка работает правильно и камера не застревает.
Ниже приведены изменения, которые необходимо внести в ваш код для реализации этих рекомендаций:
-- В функции CalcView замените секцию камеры и коллизий следующим образом: function FirstPersonView:CalcView(ply, pos, angles, fov) if not IsValid(ply) then return end if ply:Team() == self.config.spectatorTeam then return end local headPos = self:GetHeadPosition() if not headPos then return end -- Используйте фактические углы обзора игрока local playerAngles = ply:EyeAngles() -- Вычислите желаемую позицию камеры с учетом смещения local desiredCameraPos = headPos + playerAngles:Forward() * self.config.cameraOffset.x + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z -- Реализуйте обнаружение коллизий камеры if self.config.cameraCollision then local trace = {} trace.start = headPos trace.endpos = desiredCameraPos trace.filter = ply trace.mask = MASK_SOLID -- Изменено с MASK_VISIBLE_AND_NPCS на MASK_SOLID trace.min = Vector(-2, -2, -2) -- Минимальные размеры Hull trace.max = Vector(2, 2, 2) -- Максимальные размеры Hull local tr = util.TraceHull(trace) -- Используйте TraceHull вместо TraceLine if tr.Hit then local distance = tr.HitPos:Distance(headPos) if distance < self.config.maxCameraDistance then desiredCameraPos = tr.HitPos else -- Ограничьте дистанцию камеры desiredCameraPos = headPos + playerAngles:Forward() * self.config.maxCameraDistance + playerAngles:Right() * self.config.cameraOffset.y + playerAngles:Up() * self.config.cameraOffset.z end end end -- Установите позицию камеры и углы без сглаживания currentView.origin = desiredCameraPos currentView.angles = playerAngles currentView.fov = fov currentView.drawviewer = self.config.drawLocalPlayer return currentView endОбъяснение Внесённых Изменений:
-
Изменение Маски Коллизий:
trace.mask = MASK_SOLIDЭто гарантирует, что трассировка учтёт все твердые объекты, предотвращая прохождение камеры сквозь стены.
-
Использование
util.TraceHull:local tr = util.TraceHull(trace)Трассировка с использованием Hull уменьшает вероятность того, что камера случайно окажется внутри препятствия или проскользнёт мимо него из-за небольшой толщины линии.
-
Установка Размеров Hull:
trace.min = Vector(-2, -2, -2) trace.max = Vector(2, 2, 2)Эти значения задают небольшие размеры "коробки" для трассировки. Вы можете настроить эти значения в зависимости от размера вашей камеры или желаемой точности.
Дополнительные Рекомендации:
-
Тестирование и Отладка:
После внесения изменений обязательно протестируйте их в различных ситуациях (например, закрытые помещения, узкие коридоры, открытые пространства), чтобы убедиться, что камера ведёт себя ожидаемо и не застревает внутри препятствий.
-
Плавное Перемещение Камеры:
Хотя ваш текущий код устанавливает позицию камеры без сглаживания, вы можете рассмотреть возможность добавления плавного перехода при изменении позиции камеры, что сделает движение более естественным и уменьшит вероятность резких сдвигов, которые могут вызывать дисторсию или дискомфорт.
Пример реализации плавного перехода:
-- Добавьте переменную для хранения предыдущей позиции камеры local previousCameraPos = desiredCameraPos function FirstPersonView:CalcView(ply, pos, angles, fov) -- [предыдущая логика] -- Плавное перемещение камеры local lerpSpeed = 10 -- Настройте скорость currentView.origin = LerpVector(FrameTime() * lerpSpeed, previousCameraPos, desiredCameraPos) previousCameraPos = currentView.origin -- [оставшаяся логика] return currentView endПримечание: Использование
LerpVectorпозволяет камере плавно перемещаться между текущей и желаемой позицией, снижая вероятность резких перемещений и потенциальных проблем с коллизиями. -
Увеличение
cooldownдля Уведомлений об Ошибках:Если вы добавляете дополнительное логирование для отладки, убедитесь, что вы также увеличиваете время между уведомлениями, чтобы избежать спама сообщений.
-
Проверка Размеров
maxCameraDistance:Убедитесь, что значение
maxCameraDistanceадекватно для ваших нужд. Слишком маленькое значение может ограничивать свободу передвижения камеры, в то время как слишком большое может привести к непредвиденным результатам.
Заключение
Внесение этих изменений должно значительно улучшить обнаружение коллизий камеры и предотвратить её прохождение сквозь стены. Однако, всегда рекомендуется тщательно тестировать изменения в различных сценариях игры, чтобы убедиться в их эффективности и отсутствии новых проблем.
Если после внесения изменений проблема всё ещё сохраняется, рассмотрите возможность дополнительной отладки, например, визуализации трассировки коллизий с помощью
debugoverlayдля более точного определения причины. -