Mansur Nashaev
Mansur Nashaev

Reputation: 313

Unity Move rotating object

I have a ball which rotates around the point 0,0,0 in the Z-axis. When the space button is pressed, the ball has to go inside the large circle. Now my code looks like this. When you press space, the ball does not behave as they should. I want to know how to make a balloon down exactly down

that's how the ball should behave -> behavior image

my code:

void Update () {
    if (Input.GetKeyDown (KeyCode.Space)) {
        transform.position = new Vector3 (transform.position.x - 1, transform.position.y - 1, 0);
    } else {
        transform.RotateAround(new Vector3(0,0,0), new Vector3(0,0,1), 2);
    }
}

Upvotes: 1

Views: 918

Answers (1)

Happy Apple
Happy Apple

Reputation: 746

Your code to 'jump' the orbit doesn't do what you want because Transform.RotateAround modifies both the rotation and the position of the object's transform. Demonstration of how RotateAround modifies the transform

So jumping to (position - 1,1,0) in the world is going to return wildly different results every time.

What you want to do instead is calculate the (Vector) direction from the object to the centre of orbit (the difference), then scale that down to how far you want it to move, then apply it to the position.

private Vector3 _orbitPos = Vector3.zero;
private float _orbitAngle = 2f;

private float _distanceToJump = 2f;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        var difference = (_orbitPos - transform.position).normalized * _distanceToJump;
        transform.Translate(difference);
    }

    transform.RotateAround(_orbitPos, Vector3.forward, _orbitAngle);
}

This will move the object to be orbiting 2 units closer when space is pressed immediately.

If you wanted to have a smooth transition instead of a jump, look into using Mathf.Lerp, Vector3.Lerp and the routines involved.

Upvotes: 1

Related Questions