Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make a RayCast be off set?

Asked by 8 years ago

Okay so I'm Making a Ray Casting Gun. The problem I have is that I want to make a Recoil Effect on the Gun. Using math.random and Arithmetics I tried making it with this but i did not get me the results i wanted

local Vector3 = Instance.new("Vector3Value")
local x = mouse.Hit.p.X
local y = mouse.Hit.p.Y
local z = mouse.Hit.p.Z
while true do 
    wait()
    Vector3.Value.X = x
    Vector3.Value.Y = y
    Vector3.Value.Z = z
end
Vector3.Value.X = Vector3.Value.X  + math.random(1,0.5)
Vector3.Value.Y = Vector3.Value.Y + math.random(1,0.5)
Vector3.Value.Z= Vector3.Value.Z + math.random(1,0.5)
                                                --^ the offset i'm talking about. It gets called each time i fire the gun.
local x1,y1,z1 = Vector3.Value.X,Vector3.Value.Y,Vector3.Value.Y,Vector3.Value.Z


local ray = Ray.new(tool.Part.CFrame.p, (Vector3.Value - tool.Part.CFrame.p).unit * 300)
                                            -- ^ mouse.Hit.p originally goes here


Is there another way to do this? Am i Doing this wrong? Or this is just impossible?

0
Any output? gskw 1046 — 8y

1 answer

Log in to vote
0
Answered by
XAXA 1569 Moderation Voter
8 years ago

Looks like you're trying to simulate spread, not recoil. If so, the following code should help:

-- the tool
local tool = script.Parent
-- the muzzle of the gun, where the ray will start
local muzzle = tool:WaitForChild("Part") 
-- the player's mouse
local mouse = game.Players.LocalPlayer:GetMouse()

-- a variable that defines the maximum spread, in degrees
local SPREAD_DEGREES = 10

--- function called when the gun fires
function shoot()
    local start = muzzle.CFrame.p
    local mouseaim = mouse.Hit.p

    local aim = CFrame.new(start, mouseaim) -- creates a CFrame starting at muzzle looking (pointing) at where the mouse is aiming
    aim = aim * CFrame.Angles(0, 0, math.random() * 2 * math.pi) -- rotates the CFrame along its z-axis by a value between 0 and 360 degrees
    aim = aim * CFrame.Angles(math.random() * math.rad(SPREAD_DEGREES), 0, 0) -- rotate the CFrame along its x-axis by a value between 0 and SPREAD_DEGREES degrees

    local ray = Ray.new(aim.p, aim.lookVector * 300) -- cast a ray
    --TODO: check where the ray hits and act accordingly
end
0
Except is that im making a machine gun and i want the Mouse aim to update every time it moves around the screen GeezuzFusion 200 — 8y
Ad

Answer this question