- Home /
Raycast detection / lag issue
Hey everyone, I have a raycast issue, and believe me I have trolled these forums looking for an answer to my specific problem, hitherto I haven't found someone with the same problem I am having.
Here is my simple code which casts a ray forward of the "gun" and is attempting to detect what object is in front of it (by name, but I've tried by tag / Comparetag):
pragma strict
function Update () {
var length = 10;
var fwd = transform.TransformDirection (Vector3.forward);
var hit : RaycastHit;
if (Physics.Raycast (transform.position, fwd, hit)) {
var nameof = hit.collider.name;
print (nameof);
}
Debug.DrawRay(transform.position,fwd * length, Color.red);
}
There are two problems I am having with this code: 1) It will detect the name of the object, but only the first time it strikes the object and will stay "detected" until I strike a new object. So if I hit terrain, it will stay terrain until I hit cube, or some other object. 2) It is causing an unhealthy tick in the movement of the main character. When I rapidly turn or something to that effect, it will cause a bad "tick" to form. (I tried using pragma stict, but it didn't help).
I have been looking through the forums for a while and didn't find any solutions that helped, if you have an idea please let me know and thanks for your time in advance.
Just let me check - where does the value stay the same? You are not calling print unless there is a collision, so it definitely won't get updated - you'd need to do something in the "else" of the if(Physics.Raycast.
Or am I missing the point?
A glitch could be caused by what's in print, especially if it takes a long time.
Well, I shuffled the code around to this:
pragma strict
function Update () { var nameof; var length = 10;
var fwd = transform.TransformDirection (Vector3.forward);
var hit : RaycastHit;
if (Physics.Raycast (transform.position, fwd, hit)) {
nameof = hit.collider.name;
}
else{
nameof = null;
}
Debug.DrawRay(transform.position,fwd * length, Color.red);
print(nameof);
}
And it is causing the same issues (I switch to null on the else because it was crashing with it being set to hit.collider.name).
Yeah hit will be null if it didn't hit something. I'm very surprised that it isn't printing null a lot though when it doesn't hit.
BTW you can just use transform.forward rather than creating that vector fwd.
Your answer
Follow this Question
Related Questions
Why isn't hit.transform.name with ray working? 1 Answer
How to assign a Variable with a Raycast 1 Answer
Name and tag 1 Answer
Instantiating gameObejcts that can't be referred to after creation 1 Answer
Trigger and raycast error? 2 Answers