A ‘trace’, in the terms of game engines, is a physics operation that, in concept, creates a ‘line’ that goes in a single direction until it hits something.
The util.TraceLine function is the GMod Lua function to perform a trace.
Player:GetEyeTrace() is just there for convenience; it performs a trace from the eyes in the direction they are looking.
The first argument to TOOL.LeftClick (which you have called ‘trace’ in your code) is also there for convenience. It is (roughly) the same as doing self.Owner:GetEyeTrace().
In your example, you are attempting to do stuff with the variable ‘ply’.
In your mind, this is obviously the player using the tool. However, if you look at it from a coding perspective, you will notice that ‘ply’ does not exist in this situation (No ‘ply’ local in the function, nor in the file above).
For convenience, you can access the player using the tool through TOOL.Owner.
But, due to a whole load of confusing (higher level) stuff to do with Lua, metatables and Garry’s ability to confuse learners, you cannot access ‘TOOL’ when the function is running.
However, you can use ‘self’ in place of ‘TOOL’ (only within the function).
Here’s a rewrite of the function:
if not trace.Entity then return end – This is just in case the trace doesn’t hit anything. In this case, ‘trace.Entity’ would be nil, and the code below would go KABLAA at this: so you ‘return’ (stop the function running)
local physobj = trace.Entity:GetPhysicsObject()
if physobj then – I did this just in case the entity is a strange one and doesn’t have a physics object!
You may be wondering things, such as “Why is TOOL inaccessible?”, “What does ‘self’ mean?” or “What’s ‘trace’? How is it made, and why does ‘trace.Entity’ work?”, after reading this.
At this stage, try to keep your understandings as basic as possible. Only extend when you need to understand.
For example, you should consider ‘trace.Entity’ as a ‘single term’. Like the fact that ‘if CONDITION then CODE end’ just works, ‘YOUR_TRACE.Entity’ just works.
(Very primitive example, if you understand tables then you probably understand this :P)
Also, a tip: Copy and paste error messages directly as they appear in your console. You’ll have a much better chance of getting a helpful reply.
I frequently read the threads in Newbie Questions. Most of them do not have the slightest bit of care in their requests. Poor grammar and bad spelling implies they don’t give a shit about the people answering the questions, and just want an answer. Of course, I may be judging… but from what I’ve observed, the ones who have lazy original posts do not care in the end (no thanks).
You are one of the few to actually care about the people answering, and not just getting an answer.
saying that my replies are ‘extremely precious’!)
Good luck, and enjoy programming in GMLua!
(Add me on Steam if you need anything: DecoDaMan)