• trace.HitPos returns nil
    4 replies, posted
Been trying to get an entity to spawn at the position the player is looking at, but within a certain distance. Found some code that should work... but it doesn't. This is in init.lua of my gamemode. [lua] function BuyHealthKit( ply ) if ply:Team() == TEAM_SUPPLIER then local healthkit = ents.Create( "large_medkit" ) healthkit:Spawn() healthkit:SetPos( Hit ) healthkit:Activate() else ply:PrintMessage( HUD_PRINTTALK, "You must be a supplier to buy supplies!" ) end local trace = {} trace.start = ply:GetShootPos() trace.endpos = trace.start + ply:GetAimVector() * 85 trace.filter = ply local tr = util.TraceLine(trace) local Hit = tr.HitPos end function BuyM4( ply ) if ply:Team() == TEAM_SUPPLIER then local M4 = ents.Create( "wep_m4" ) M4:Spawn() M4:SetPos( tr.HitPos ) M4:Activate() else ply:PrintMessage( HUD_PRINTTALK, "You must be a supplier to buy supplies!" ) end local trace = {} trace.start = ply:GetShootPos() trace.endpos = trace.start + ply:GetAimVector() * 85 trace.filter = ply local tr = util.TraceLine(trace) local Hit = tr.HitPos end [/lua] When I try to spawn the M4 I get the error Expedition/gamemode/init.lua:246: attempt to index global 'tr' (a nil value) And when I spawn the Healthkit I get the error Expedition/gamemode/init.lua:227: bad argument #1 to 'SetPos' (Vector expected, got nil) This should be working, I looked at some code from the wiki and some other gamemodes, and I don't see whats wrong with it. When I used [lua] local tr = ply:GetEyeTrace entity:SetPos( tr.HitPos ) [/lua] It worked fine, but spawned the ent at the place you were looking at even if it was on the other side of the map.
You're doing it wrong. It should be: [code] ... tr = util.TraceLine( trace ) local Hit = tr.HitPos ... M4:SetPos( Hit ) M4:Spawn( ) [/code] When you're calling it, Hit was nil since you haven't traced yet.
So your saying I need to out the code for the trace before the actaul SetPos?
Yes
Worked like a charm, thank you very much.
Sorry, you need to Log In to post a reply to this thread.