For a gamemode I’m working on I’m making a SWEP that lets you attach things to a vehicle via a rope. If the player is pointing at a towable object and they are within range of a towing vehicle, I’d like to render a preview rope.
This is causing me more difficulty than I had anticipated.
The code I’d like to have looks a bit like this:
local rope = Material("cable/rope") function SWEP:ViewModelDrawn() local trc = self:OwnerTrace(self.RopeLength) print(trc.Entity) if self:ValidTarget(trc.Entity) then print("drawing") local towPoint = self:FindClosestTowPoint(trc.HitPos) if towPoint then render.SetMaterial(rope) render.DrawBeam(towPoint:GetPos(), trc.HitPos, 1, 0, 0, Color(255, 255, 255, 255)) end end end
Unfortunately there are two issues here:
- Render functions in the ViewModelDrawn hook is drawn in slightly the wrong location. Additionally, Vector:ToScreen() returns slightly incorrect coordinates. These imperfections are more noticeable the further the player is from the points that are being rendered.
- Stuff drawn in the ViewModelDrawn hook is displayed on top of all world geometry and doesn’t respect z index.
I have tried a bunch of other hooks, some documented in the wiki and others undocumented but mentioned in weird places on the internet:
Interestingly enough, according to some hastily inserted print(“test”) lines, none of these are actually ever executed. My SWEP has both a world model and a view model.
The closest I’ve managed to get is:
function SWEP:DrawHUD() local trc = self:OwnerTrace(self.RopeLength) print(trc.Entity) if self:ValidTarget(trc.Entity) then print("drawing") local towPoint = self:FindClosestTowPoint(trc.HitPos) if towPoint then local start = towPoint:GetPos():ToScreen() local endpos = trc.HitPos:ToScreen() print(start.x, start.y, "", endpos.x, endpos.y) cam.Start2D(); surface.SetDrawColor(Color(100, 255, 100)) surface.DrawLine(start.x, start.y, endpos.x, endpos.y) cam.End2D(); end end end
This displays a green line between the correct positions, but is not a desirable solution for the following reasons:
- The line doesn’t take into account perspective. I could theoretically fix this by drawing a polygon, but that seems like overkill
- The line is a solid colour rather than textured. Again, polygons could solve this.
- The line draws on top of all world geometry and does not respect z indexes.
Hopefully you geniuses will be able to help me out, I hope I’ve explained the situation clearly.