控制2点之间的起点和终点对象

Control begin and end point object between 2 points

我试图在 2 点之间统一移动一个对象,目前它有点奇怪,我阅读了文档,它说对象开始点是 (0,0,0) 所以我的对象去了在我的另一个网格下,我可以实际控制终点,在我的例子中是 10,我希望对象在 1.5 和 10 之间移动(不是 0 到 10) 我有这个

void Update () {
    transform.position = new Vector3(transform.position.x,Mathf.PingPong(Time.time,10.0f), transform.position.z);
}

当我尝试在球上加速时这样做:

void Update () {
    transform.position = new Vector3(transform.position.x,Mathf.PingPong(Time.time,10.0f) * 10, transform.position.z);
}

对象没有碰撞并在终点返回它只是停止循环并且再也没有回来我该如何解决这 2 个问题?

如果您的对象有碰撞体,我建议您通过其刚体而不是变换来移动它,以避免潜在的碰撞问题。试试这个:

public float MinY = 1.5f; // y position of start point
public float MaxY = 10f; // y position of end point
public float PingPongTime = 1f; // how much time to wait before reverse
public Rigidbody rb; // reference to the rigidbody

void Update()
{
     //get a value between 0 and 1
     float normalizedTime = Mathf.PingPong(Time.time, PingPongTime) / PingPongTime;
     //then multiply it by the delta between start and end point, and add start point to the result
     float yPosition = normalizedTime * (MaxY - MinY) + MinY;
     //finally update position using rigidbody 
     rb.MovePosition(new Vector3(rb.position.x, yPosition, rb.position.z));
}

在这里你可以更好地控制行进距离和速度。 其实我没有得到你所面临的问题到底是什么。但是不要忘记这里和你的尝试,你是在直接修改对象的位置,而不是添加力或其他。

希望对你有帮助。

我认为您只是误解了 Mathf.PingPong 方法的工作原理:

  • 第一个参数 t 是您想要 "clamp" 在 0 和给定的 长度之间的值 :这是你想要像你所做的那样放置 Time.time 的地方,因为这个值会随着时间的推移而增加,因此会永远振荡。如果你想 increase/decrease 振荡速度,你必须乘以它。
  • 第二个参数 length 是 "clamp" 的最大值:如果你想 increase/decrease 距离(在你的情况下) 你要么将它设置为 0 并将整个 Mathf.PingPong(...) 乘以一个值,要么直接给它想要的值(两种实现都会有不同的效果。

  • Mathf.PingPong(Time.time * speed, 1.0f) * value : speed会影响振荡速度/value会影响达到的最大值并且完成振荡(来回)的速度/时间将保持不变,因为 value 变化并随着 speed 增加

  • Mathf.PingPong(Time.time * speed, value) : speed 将影响振荡速度 / value 将影响达到的最大值但不影响速度 /完成振荡(来回)的时间将随着 value 的增加而增加,随着 speed 的增加
  • 而减少

关于您的其他问题:

如果你想在 1.510 之间移动你的对象,你必须这样写: transform.position = new Vector3(transform.position.x, 1.5f + Mathf.PingPong(Time.time, 10.0f - 1.5f), transform.position.z);.

此外,如果您想检测碰撞,请避免手动设置位置,因为它会扰乱物理并导致奇怪的行为。在保持物理工作的同时移动对象的最佳方法是按照@Heldap 所说的使用 Rigidbody.MovePosition.