Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.