简体   繁体   中英

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);
    }
}

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. 演示 RotateAround 如何修改变换

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM