C# 物体上下移动但不向左移动

C# 物体上下移动但不向左移动,c#,unity3d,C#,Unity3d,如果我取出void Update()中的代码,对象将向左移动。否则,对象将仅在同一x轴上上下移动 public class movingRockUpScript : MonoBehaviour { public Rigidbody2D rgbody; public Vector2 velocity = new Vector2(-4, 0); Vector2 _start = new Vector2(0,-8); Vector2 _end = new Vector2(0,

如果我取出
void Update()
中的代码,对象将向左移动。否则,对象将仅在同一x轴上上下移动

 public class movingRockUpScript : MonoBehaviour {
   public Rigidbody2D rgbody;
   public Vector2 velocity = new Vector2(-4, 0);
   Vector2 _start = new Vector2(0,-8);
   Vector2 _end = new Vector2(0,-3);
   public float _speed = 1f;
   // Start is called before the first frame update
   void Start()
   {
       rgbody = GetComponent<Rigidbody2D>();
       rgbody.velocity = velocity;
       transform.position = new Vector3(transform.position.x + Random.Range(1,5), transform.position.y, transform.position.z);
   }

   // Update is called once per frame
   void Update()
   {
       float t = Mathf.PingPong(Time.time, _speed) / _speed;
       transform.position = Vector2.Lerp(_start, _end, t);
   }
}
公共类movingRockUpScript:MonoBehavior{
公共刚体;
公共向量2速度=新向量2(-4,0);
向量2 _start=新向量2(0,-8);
向量2 _end=新向量2(0,-3);
公共浮标_速度=1f;
//在第一帧更新之前调用Start
void Start()
{
rgbody=GetComponent();
rgbody.velocity=速度;
transform.position=新矢量3(transform.position.x+随机范围(1,5),transform.position.y,transform.position.z);
}
//每帧调用一次更新
无效更新()
{
float t t=Mathf.PingPong(Time.Time,_speed)/_speed;
transform.position=Vector2.Lerp(_start,_end,t);
}
}

我试着将
rgbody.velocity
放在
Update()
中,但这并没有改变任何事情。

如果你想将速度和乒乓球运动结合起来,你可能只需要为两者设置一个运动轴。不要直接设置变换并使用
Vector2.Lerp
,而是只在位置的y分量上使用
Mathf.Lerp

public class movingRockUpScript : MonoBehaviour {
    public Rigidbody2D rgbody;
    public Vector2 velocity = new Vector2(-4, 0);
    Vector2 _start = new Vector2(0,-8);
    Vector2 _end = new Vector2(0,-3);
    public float _speed = 1f;
    // Start is called before the first frame update
    void Start()
    {
        rgbody = GetComponent<Rigidbody2D>();
        rgbody.velocity = velocity;
        transform.position = new Vector3(transform.position.x + Random.Range(1,5), transform.position.y, transform.position.z);
    }
    
    // Update is called once per frame
    void Update()
    {
        float t = Mathf.PingPong(Time.time, _speed) / _speed;
        transform.position = new Vector2(transform.position.x, Mathf.Lerp(_start.y, _end.y, t));
    }
}
公共类movingRockUpScript:MonoBehavior{
公共刚体;
公共向量2速度=新向量2(-4,0);
向量2 _start=新向量2(0,-8);
向量2 _end=新向量2(0,-3);
公共浮标_速度=1f;
//在第一帧更新之前调用Start
void Start()
{
rgbody=GetComponent();
rgbody.velocity=速度;
transform.position=新矢量3(transform.position.x+随机范围(1,5),transform.position.y,transform.position.z);
}
//每帧调用一次更新
无效更新()
{
float t t=Mathf.PingPong(Time.Time,_speed)/_speed;
transform.position=newvector2(transform.position.x,Mathf.Lerp(_start.y,_end.y,t));
}
}

让我知道这是否是您想要的结果。

您到底想要实现什么?
Update
中的代码直接将位置分配给
\u end
是什么,即
新向量2(0,-3),这意味着它将只更改y。当你在这里直接设置位置时,它将覆盖你正在设置的任何速度。对象将在向左移动的同时上下移动,直到它脱离屏幕并被销毁。是的,这非常有效!