Unity-无法使对象振动/悬停在适当位置?

时间:2018-12-05 21:26:35

标签: c# unity3d game-physics game-development

好吧,我有一堆立方体,我只需要在太空中缓慢地振动/摇动,就好像几乎在盘旋一样。我首先尝试使用带有噪音的粒子发射器,但无法获得运动部分。我现在尝试通过将脚本附加到每个对象来进行尝试:

 float speed = 1.0f; //how fast it shakes
    float amount = 1.0f;
   public  Vector2 startingPos;

    void Awake()
    {
        startingPos.x = transform.position.x;
        startingPos.y = transform.position.y;
    }

    // Update is called once per frame
    void Update()
    {

        float newx = startingPos.x + (Mathf.Sin(Time.time * speed) * amount);
        float newy = startingPos.y + (Mathf.Sin(Time.time * speed) * amount);

        transform.position = new Vector3(newx, newy, transform.position.z);

    }

这样,立方体完全消失了。 Ive在论坛上无济于事-我该怎么做才能使多维数据集仅在原处振动/悬停?

2 个答案:

答案 0 :(得分:0)

理想情况下,至少在像这样的小规模情况下,您会使用LeanTween之类的包来处理过渡/动画。

基本上,过程是这样的:

On Start:
    store 'starting' position

On Enabled:
    Run DoHover

On DoHover:
    Pick random offset within radius (Random.insideUnitCircle() * radius)
    LeanTween current transform to startingPos + offset over timeDelay
    Set LeanTween.OnComplete to run DoHover

如果确定不使用第三方程序包来管理补间,则可以尝试一下(我使用3D场景,但您应该能够轻松地展平它):

    private const float threshold = 0.02f;

    private Vector3 startingPos;
    private Vector3 destinationPos;
    private Vector3 velocity;
    public float radius = 0.1f;
    public float minTimeDelay = 0.1f;
    public float maxTimeDelay = 0.3f;

    private void Start() {
        startingPos = destinationPos = transform.position;
    }


    // This is a 'physics' frame update
    public void FixedUpdate() {

        if ( Vector3.Distance(transform.position, destinationPos) < threshold ) {
            // Pick new destination and speed
            destinationPos = startingPos + Random.insideUnitSphere * radius;
            velocity = (destinationPos - transform.position) / Random.Range(minTimeDelay, maxTimeDelay);
        }

        // Move toward destination
        transform.position += velocity * Time.fixedDeltaTime;
    }

答案 1 :(得分:0)

我今天使用三个叠加的 Sin 波解决了这个问题;它很简单,并提供了一个很好的随机悬停圆形效果,并且不需要跟踪对象在哪里/曾经在哪里:

transform.position.x = originalPosition.x + hoverSpeed * (
    Mathf.Sin(Time.time / 3) 
    + Mathf.Sin(Time.time / 7) 
    + Mathf.Sin(Time.time / 11)
    );

transform.position.y = originalPosition.y + hoverSpeed * (
    Mathf.Sin(Time.time / 2) 
    + Mathf.Sin(Time.time / 5) 
    + Mathf.Sin(Time.time / 13)
    );

我也在 originalPosition 启动对象,然后通过将 hoverSpeed 启动为零并执行以下操作逐渐向外移动:

hoverSpeed = Mathf.Clamp(hoverSpeed + Time.deltaTime, 0, hoverMaxSpeed);