Raycast in Update() stuttering in game mode - sudden issue

I am launching a ray from the center of the viewport into the world. I am casting many rays and doing lots of stuff in update - and none of them are stuttering. This specific ray from the viewport is stuttering. Last night everything was fine, but in the morning this issue occurred. So this proves that this isn’t due to some change I made. The stuttering only happens in game mode, not scene mode

What are some possible problems / solutions?

My code is very simple as well. Please see below. When I draw the aimRay I can see it stutter. Same for aimTarget, it stutters. Thank you so much

public void aimGun(PlayerWeapon playerWeapon)
    {
        Ray aimRay = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;
        if (Physics.Raycast(aimRay, out hit, playerWeapon.range))
        {
            aimTarget.transform.position = hit.point;
        }
        else
        {
            aimTarget.transform.position = mainCamera.transform.position + aimRay.direction.normalized*playerWeapon.range;
        }

        aimTarget.transform.LookAt(this.transform);
        aimTarget.transform.forward = -aimTarget.transform.forward;

        playerWeapon.setHitPoint(hit);
        playerWeapon.setAimTarget(aimTarget.transform);
        playerWeapon.setAttacker(this.transform);
    }

What does “stutter” mean? Do you see a drop in framerate? Did you profile?

Nothing about the code seems suspicious, set aside the repetitive access of aimTarget.transform which isn’t a performance problem but one of readability.

By stutter I mean the ray doesn’t follow my mouse movement. Instead it looks like it lags behind a few coordinates before aligning to the center of the screen.

None of the other rays I cast have this issue

You’ll need to call aimGun from LateUpdate.

BTW - Lines 14 and 15 can be replaced with:

aimTarget.transform.rotation=transform.rotation;

Why late update and not update?

It guarantees that your aimGun function is always executed after the code that moved your camera. Although this is assuming your camera was updated from an Update somewhere.

1 Like