I added the arrow getting stuck in its target

So, for aiming at the target we adjust by the CapsuleCollider in order not to just shoot at the target’s feet (although right now we could as well be shooting there since nothing is making the target feel any pain yet).

I also added some detection of “are we there yet?”, e.g. when the arrow hits the target, it stops moving forward (which solves the “arrow flips forward and backwards” issue).

Next step was re-parenting the projectile to the target, so it be moving along if the player moves after being hit. But just parenting just to the target has one issue: it’s positioned by the “shell” object (the target prefab’s root) and doesn’t take into account the movement of the idle animation (probably less of an issue while moving around).

So I tried to select a suitable bone of the target’s rig and stuck the arrow to it. Since the rig’s “Root” is also stationary I chose to go with the “Hips”.
Unfortunately the Transform.Find() method seems not to be recursive so I had to do a bit of traversal in the hierarchy myself. Not that I went with Child(0) as the starting point to accommodate for different models.

        private Vector3 targetAimLocation = Vector3.zero;
        Transform targetRootBone = null;

        private void Start()
        {
            if (null == target)
            {
                // For the debugging phase...
                target = GameObject.FindGameObjectWithTag("Player").transform;

                // Find() apparently is not recursive, so we have to climb down the hierarchy...
                targetRootBone = target.GetChild(0).Find("Root").Find("Hips");
            }

            // We do this only once, for performance and since arrows are no
            // homing missiles. We may have to get more fancy if we add magic
            // missiles that *might* be following the target...
            targetAimLocation = GetAimLocation();
        }

        private void Update()
        {
            if (null == target) return;

            if (Vector3.SqrMagnitude(target.position - transform.position) > targetHitDistance)
            {
                transform.LookAt(targetAimLocation);
                transform.Translate(speed * Time.deltaTime * Vector3.forward);
            }
            else
            {
                GetComponent<Projectile>().enabled = false;
                transform.SetParent(targetRootBone);    // Re-parent to make the arrow get stuck on the target
            }
        }


Once the projectile is properly spawned there is no use in grabbing a target from the scene, but locating its bone would work the same.

The target having moved away in the meantime isn’t handled so far (I suppose some proper hit detection will be added during one of the upcoming lessons).

Privacy & Terms