团结-移动对象直到点

时间:2018-09-13 10:36:26

标签: c# unity3d

我正在使用下面的代码将Ball移动到确定的点。但是,球正在“传送”到那儿,我如何将球滚动到该点?

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");
            }
}

2 个答案:

答案 0 :(得分:2)

您可以使用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);

答案 1 :(得分: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);
}

此外,如果要在到达目标点时立即停球,则可以在GetComponent<Rigidbody>().velocity时将targetPoint - transform.position = 0设置为0

希望对您有帮助。