简体   繁体   English

unity 移动旋转物体

[英]Unity Move rotating object

I have a ball which rotates around the point 0,0,0 in the Z-axis.我有一个围绕 Z 轴上的 0,0,0 点旋转的球。 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.您“跳跃”轨道的代码不会执行您想要的操作,因为Transform.RotateAround修改了对象变换的旋转和位置。 演示 RotateAround 如何修改变换

So jumping to (position - 1,1,0) in the world is going to return wildly different results every time.因此,每次跳转到世界中的 (position - 1,1,0) 都会返回截然不同的结果。

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.当立即按下空格键时,这会将要绕轨道运行的物体移近 2 个单位。

If you wanted to have a smooth transition instead of a jump, look into using Mathf.Lerp , Vector3.Lerp and the routines involved.如果您想要平滑过渡而不是跳转,请考虑使用Mathf.Lerp 、 Vector3.Lerp 和所涉及的例程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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