llamacademy / scriptable-object-based-guns

Learn how to create a ScriptableObject-based gun system from scratch for your game!
https://www.youtube.com/watch?v=E-vIMamyORg&list=PLllNmP7eq6TQJjgKJ6FKcNFfRREe_L6to
MIT License
119 stars 27 forks source link

The bullet trajectory appears broken #18

Open wkyfasttank opened 3 months ago

wkyfasttank commented 3 months ago

When I was writing code following your first gunfight system tutorial, I found that after firing a few shots, the bullet trajectory started not at the muzzle, but in the direction of the last call to the trajectory. As shown in the figure: 微信图片_20240721202704 Later I thought that it might be because TrailRenderer did not clear the object data when it was recycled into the object pool. Then I added "instance.Clear();" to the PlayTrail method code in the GunScriptableObject class to solve the problem. The code is as follows (add code in the commented part):

        private IEnumerator PlayTrail(Vector3 startPoint, Vector3 endPoint, RaycastHit hit)
        {
            Debug.Log(startPoint+","+endPoint);
            TrailRenderer instance = _trailPool.Get();
            instance.gameObject.SetActive(true);
            instance.transform.position = startPoint;
            yield return null;
            instance.emitting = true;
            float distance = Vector3.Distance(startPoint, endPoint);
            float remainingDistance = distance;
            while (remainingDistance > 0)
            {
                instance.transform.position = Vector3.Lerp(startPoint, endPoint,
                    Mathf.Clamp01(1 - (remainingDistance / distance)));
                remainingDistance -= trailConfig.simulationSpeed * Time.deltaTime;
                yield return null;
            }

            instance.transform.position = endPoint;
            yield return new WaitForSeconds(trailConfig.duration);
            yield return null;
            // instance.Clear();
            instance.gameObject.SetActive(false);
            _trailPool.Release(instance);
        }

I want to know why you can still make the bullet trails not appear broken without clearing the TrailRenderer data。 I'm sorry for my poor English,Thanks for your tutorial,love from china.

llamacademy commented 3 months ago

What happens if you flip

instance.gameObject.SetActive(true);
instance.transform.position = startPoint;

to

instance.transform.position = startPoint;
instance.gameObject.SetActive(true);

I do remember facing this issue at one point. If you clear the trail that is also a perfectly acceptable solution if my suggestion does not work.

wkyfasttank commented 3 months ago

It work,thank so much.