Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Virtual Reality VR in Unity Physics Scripting Returning Objects with a Coroutine

Ball return is instantaneous

So the code is all working great except the ball teleports into my hand, I've adjusted objectReturnSpeed several times even down to 1F and still no luck. Here is my ReturnObject code. I'm frankly stumped as to what I did wrong.

IEnumerator ReturnObject()
    {

        float distanceThreshold = 0.1f;

        // While there is still a small amount of distance between the thrown object and the starting position
        while (Vector3.Distance(throwingObject.transform.localPosition, startingPosition)> distanceThreshold)
        {
            // ... move the ball toward the starting position
            throwingObject.transform.localPosition = Vector3.Lerp(throwingObject.transform.localPosition, 
                                                    startingPosition, 
                                                    Time.deltaTime * objectReturnSpeed);
            // ...if the thrown object is now close to the start position...

            if(Vector3.Distance(throwingObject.transform.localPosition, startingPosition) < distanceThreshold)
            {

                // ...then resent the position directly
                throwingObject.transform.localPosition = startingPosition;
            }
        }
        //... Yield back control to the main script
        yield return null;

    }

1 Answer

Nick Pettit
STAFF
Nick Pettit
Treehouse Teacher

Hi Robert!

Hard to tell from this code snippet, but my guess is that startingPosition is somehow set incorrectly. If you're still having trouble, upload a zip of the project somewhere and paste the link here and I can take a look.

I think you are right Nick, I copied your code in the Room Scale zip and changed nothing else and it worked like a charm so I'll revert the changes and put them side-by-side and figure out what's off.