【问题标题】:Unity - Move object until pointUnity - 将对象移动到点
【发布时间】:2018-09-13 10:36:26
【问题描述】:

我正在使用下面的代码将球移动到确定的点。但是,球正在“传送”到那里,我怎样才能将球滚动到该点?

void Update(){
            if (Input.GetMouseButtonDown(0) && EventSystem.current.currentSelectedGameObject != ButtonDiminuir && EventSystem.current.currentSelectedGameObject != ButtonAumentar &&
       EventSystem.current.currentSelectedGameObject != BarraForca) {
                    transform.position = Vector3.Lerp(transform.position, new Vector3(transform.position.x, transform.position.y, -9.0424f), 2 * Time.deltaTime);
                    Anim.Play("Kick_Up");
            }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

您可以使用Vector3.Lerp 这样做:

Vector3 startPosition;
Vector3 endPosition;
var speed = 10.0;

transform.position = Vector3.Lerp(startPosition, endPosition, speed * Time.deltaTime);

或使用Vector3.MoveTowards

// The step size is equal to speed times frame time.
float step = speed * Time.deltaTime;

// Move our position a step closer to the target.
transform.position = Vector3.MoveTowards(transform.position, target.position, step);

【讨论】:

  • 注意,像这样使用第一个sn-p,它几乎不会动! Lerp 根据第三个参数(在 0 和 1 之间)在开始和结束位置之间进行插值。 Time.deltaTime 取决于帧速率,通常类似于1/60 s => 您始终将插值设置为固定在10 * 1/60 = 1/6。它永远不会到达1。开始时,您需要在每一步执行passedTime+= Time.deltaTime 之前使用passedTime = 0。比在Lerp 中使用这个代替Vector3.Lerp(start, end, speed * passedTime)
  • 我会尝试回来我会带来答案
  • Z3RP,我认为你的代码有效。但是球只是为 Update() 做了一个步骤,有一种方法可以在第一个 Update() 调用中立即运行吗?我将更新我的问题的代码
  • @L.Th 在您的更新方法中,您在每次更新被称为新时设置结束和开始位置。尝试在开始时设置它并在结束时将其设置为 null :)
  • 哇哦!非常好。有用!非常感谢!
【解决方案2】:

如果您想滚动球,请使用AddForce() 而不是transform.position

首先,将RigidbodySphere Collider 添加到您的球类游戏对象中。

然后试试这段代码:

public Vector3 targetPoint;
public float forceAmount;

...

void Update()
{
    Vector3 force = ((targetPoint - transform.position).normalized * forceAmount * Time.smoothDeltaTime);
    GetComponent<Rigidbody>().AddForce(force);
}

另外,如果你想球到达目标点后立即停止,你可以在targetPoint - transform.position = 0时将GetComponent&lt;Rigidbody&gt;().velocity设置为0

希望对你有帮助。

【讨论】:

  • 我试过AddForce(),但它对我不起作用,我会像你展示的那样尝试,稍后我会带来一些答案
猜你喜欢
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
相关资源
最近更新 更多