Skip to content

Raycasting

DynamicCrosshair uses Roblox's Raycasting to return a origin and direction from the camera to a random world position in between the crosshair.

Code:

Setting The Radius
1
2
3
4
5
local UI : ScreenGui = ...
local DynamicCrosshair = require(...).New(UI)
DynamicCrosshair:Enable()

local origin, direction = DynamicCrosshair:Raycast()

Note

The raycast will always originate from the camera position, currently there is no way to change this.

Example:

In this video, raycast are repeatly shot out creating a bullet tracing effect.

Note

This is a localscript located under a ScreenGui

Code Example
local RunService = game:GetService('RunService')
local UserInputService = game:GetService('UserInputService')
UserInputService.MouseIconEnabled = false

local UI = script.Parent
local DynamicCrosshair = require(script:WaitForChild('DynamicCrosshair')).New(UI)

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

DynamicCrosshair:Enable()
DynamicCrosshair:Max(120)
DynamicCrosshair:Min(60)

local function CreateBullet(ray, origin, direction)
    local intersection = ray and ray.Position or origin + direction
    local distance = (origin - intersection).Magnitude

    local bullet_clone = Instance.new("Part")
    bullet_clone.Material = Enum.Material.Neon
    bullet_clone.Size = Vector3.new(0.1, 0.1, distance)
    bullet_clone.CFrame = CFrame.new(origin, intersection)*CFrame.new(0, 0, -distance/2)
    bullet_clone.Parent = game.Workspace.Bullets    
    bullet_clone.Anchored = true
    bullet_clone.CanCollide = false
end

local function Click()
    -- shove crosshair
    DynamicCrosshair:Shove()

    -- raycast

    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Blacklist
    params.FilterDescendantsInstances = {Player.Character, workspace.Bullets, workspace.CurrentCamera}
    local origin, direction = DynamicCrosshair:Raycast()
    local ray = workspace:Raycast(workspace.CurrentCamera.CFrame.Position, direction*50000, params)

    CreateBullet(ray, origin, direction)    
end

RunService.RenderStepped:Connect(RenderStepped)
Mouse.Button1Down:Connect(Click)