简体   繁体   English

改变正弦函数的相位

[英]Change phase in sine function

I need some help with mathematics in my Unity game. 我在Unity游戏中需要一些数学方面的帮助。 Here is the concept: Ball moves up and down using sine function (blue line). 这里是概念:使用正弦函数(蓝线)上下移动球。 In any moment of time player may want to press space bar and change direction of ball according to red line. 在任何时候,玩家可能需要按空格键并根据红线更改球的方向。 As example, I've chosen pi/4. 例如,我选择了pi / 4。

  • The ball must save it's position on y axis 球必须保存其在y轴上的位置
  • it must invert it's vertical motion. 它必须反转垂直运动。

So the change should be smooth, I think, with no unnatural jumps. 因此,我认为变化应该是平稳的,没有不自然的跳跃。

Plot: 情节:

在此处输入图片说明

Here is my class: 这是我的课:

public class GoForward : MonoBehaviour
{
    public float speed = 0.1f; // speed of forward motion
    public float amplitude = 5f; // strength of vertical motion
    public float frequency = 5f; // width of spikes of vertical motion

    // Update is called once per frame
    void Update ()
    {
        float phase = 0f; // phase displacement

        if (Input.GetKeyDown (KeyCode.Space))
        {
            // find phase displacement here
        }

        // apply new position to the ball
        float xpos = transform.position.x + speed * Time.deltaTime;
        float ypos = amplitude * Mathf.Sin (frequency * Time.time + phase);
        transform.position = new Vector3 (xpos, ypos, transform.position.z);
    }
}

Of course, I think solution is simpliest, but my mind can't concentrate. 当然,我认为解决方案是最简单的,但是我不能专心。 So I need your help, guys. 伙计们,我需要您的帮助。

I need to find phase displacement in any moment of time, so that all my conditions must hold. 我需要随时找到相位偏移,以便我的所有条件都必须成立。

Thanks! 谢谢!

Solution found. 找到解决方案。 Thank all of you a lot for help! 非常感谢大家的帮助!

For a given time Time.time of the first half phase, the distance to the sine maximum is 对于前半阶段的给定时间Time.time ,到正弦最大值的距离为

dist = Pi/2 - frequency * Time.time

You need to offset the curve by twice the distance (up the hill, then down the same amount). 您需要将曲线偏移两倍的距离(上山,然后下移相同的数量)。 So you need: 因此,您需要:

if (Input.GetKeyDown (KeyCode.Space))
{
    phase = Pi - 2 * frequency * Time.time - oldPhase;
}

This also works for the second half phase. 这也适用于后半阶段。

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

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