1
\$\begingroup\$

So I've been trying to make a simple sphere-orbiting-another-sphere test. The smaller sphere is supposed to circle the bigger one based on the mouse location.

Here is my code:

    //script is assigned to the smaller sphere
    screenpos = Camera.main.ScreenToWorldPoint (Input.mousePosition); 

    if (screenpos.x <= centerball.x + 2f && screenpos.x >= centerball.x - 2f) //orbit radius is 2
    {
        xpos = screenpos.x;
        ypos = (Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+centerball.y; 
        //generated value of y from an equation
        //equation of circle -> y = sqrt[(r^2)-(x-h)^2]+k

        if(screenpos.y <= centerball.y) 
        {
            ypos = -(Mathf.Sqrt(4f-Mathf.Pow((xpos - centerball.x),2)))+ centerball.y;
            //equation of circle when square root has negative sign
        }

    transform.position = new Vector3(xpos ,ypos,0); 

The code is quite straightforward. Basic math equations and all. And it works all fine except for when xpos gets close to the values of "centerball.x ± 2f ".

It stops moving as I approach the value and then jerks forward, skipping an entire set of values of ypos in between.

So I checked my formula and it is absolutely correct. There is no value of xpos where ypos cannot be obtained (no negative squares).

I did a little thinking and came to the possible conclusion that the value of screenpos was rounded off too much (debug.log showed only 1 decimal place), causing the value of ypos to lose accuracy and jump as the value of xpos approached the previously mentioned bounds. If this is the cause, is there a way to record screenposition more accurately or any other way to get around this problem?

And if this is NOT the cause, can someone please explain what is going on here?

\$\endgroup\$
1
\$\begingroup\$

A much simpler approach to this would be to use vector math. I'm assuming you're trying to get the closest point to the mouse on the outer sphere. All you really have to do is get the vector from your center point to the mouse point, normalize, and then multiply by the radius of your sphere.

screenpos = Camera.main.ScreenToWorldPoint (Input.mousePosition); 
Vector3 toMouse = screenpos - centerball;
transform.position = centerball + toMouse.Normalize() * radius;
\$\endgroup\$
0
\$\begingroup\$

I figured this problem out a little while ago. Trick is to just use polar equations for the orbit motion. Does the job perfectly, though I still do not know exactly why the cartesian equation did not work. Anyway, thanks Urist for your response.

\$\endgroup\$

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.