0
\$\begingroup\$

If the player clicks an object to move the player sprite to the object and interact with it, how do I wait until the player has reached the gameObject to perform the interaction?

I have the interaction hooked up okay, but it is executing as soon as the click occurs. I would like the order instead to be (player clicks on object) (player walks to object) (once player is close enough to object the interaction occurs). But if the player moves away before reaching the object then the interaction is cancelled.

I'm not sure if I should use the object's onTrigger? But my question is if I use onTriggerEnter for the gameObject, and then the player cancels the interaction before reaching it, how do I cancel the ontrigger? Is there a better way? Also, I cannot always use an onTriggerEnter because sometimes it is clicking on an empty tile and I want to wait until the player has reached the tile.

Thanks!

\$\endgroup\$
0
\$\begingroup\$

Okay, fixed this with

/*
 * Postpones the ineraction with the clicked on object until the player
 * has arrived.
 */
void WaitUntilArrivalToInteract(Vector3 clickedWorldPosition,
                                TileBase clickedGroundTile) {
    atDestinationCoroutine = WaitAndHandleClickInteraction(clickedWorldPosition,
                                                           clickedGroundTile);
    StartCoroutine(atDestinationCoroutine);
}

/*
 * Waits until the player is within a specific distance to interact with
 * the target object. 
 */
public IEnumerator WaitAndHandleClickInteraction(Vector3 clickedWorldPosition,
                                                 TileBase clickedGroundTile) {
    yield return new WaitUntil(() => {
        float remainingDistance = (transform.position - targetPoint).sqrMagnitude;
        return remainingDistance < Constants.DISTANCE_UNTIL_AT_DEST;
    });
    HandleClick(clickedGroundTile, clickedWorldPosition);
}

And I think I should be able to interrupt this by stopping the coroutine.

\$\endgroup\$
  • \$\begingroup\$ you can also use something like var dist = Vector3.Distance(a,b); \$\endgroup\$ – Justin Markwell May 5 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.