How do i raycast in the camera current position and how do i make the viewmodel move backwards

  1. What do you want to achieve? Keep it simple and clear!

im creating a system where if the cameras position is close to a wall then the viewmodel backs up, but i have issues raycasting.

mainly the issues is that i dont know where the camera is currently facing so how would i know where the camera is currently facing?

1 Like

Fairly simple, take camera’s look vector as direction.

local camera = workspace.CurrentCamera

local RAY_LENGTH = 5

game:GetService("RunService").Heartbeat:Connect(function(dt)
	local rayResult = workspace:Raycast(
		camera.CFrame.Position, camera.CFrame.LookVector * RAY_LENGTH
	)
	if rayResult then
		print(rayResult.Instance)
	end
end)

Usually raycast params are also needed to exlude the view model itself.

1 Like

thanks, sorry but can you explain how do i make the viewmodel move backwards does have to do with the distance

1 Like

Alright.

I put together a standalone demo in StarterCharacterScripts using a basic part as a view model. When moving a model, you have to use other methods like PivotTo().

The above snippet is extended with raycast params to ignore the view model and player’s own character. The new script has an offset variable, which equals to a CFrame constructed based on how far away the hit object is.

RAY_LENGTH is an arbitrary value. If the ray intersection is at distance rayResult.Distance, then the remaining ray length is RAY_LENGTH - rayResult.Distance, and that’s how far back we push the view model.

local RunService = game:GetService("RunService")

local BASE_OFFSET = CFrame.new(0, -1.5, -3)
local RAY_LENGTH = 5

local player = game:GetService("Players").LocalPlayer
local camera = workspace.CurrentCamera
local character = player.Character or player.CharacterAdded:Wait()

local offset = CFrame.new()

local viewModel = Instance.new("Part")
viewModel.Anchored = true
viewModel.CanCollide = false
viewModel.Size = Vector3.new(2,1,1)
viewModel.Name = "ViewModel"
viewModel.Parent = camera

local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {viewModel, character}
rayParams.FilterType = Enum.RaycastFilterType.Exclude

RunService:BindToRenderStep("ViewModelUpdate", Enum.RenderPriority.Camera.Value +1, function(dt)	
	local rayResult = workspace:Raycast(
		camera.CFrame.Position, camera.CFrame.LookVector * RAY_LENGTH, rayParams
	)
	if rayResult then
		print(rayResult.Instance)
		offset = CFrame.new(0, 0, RAY_LENGTH - rayResult.Distance)
	else
		offset = CFrame.new()
	end
	
	viewModel.CFrame = camera.CFrame * BASE_OFFSET * offset
end)
2 Likes

i modified the code and it worked thank you so much!

1 Like

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