0

我想要一个脚本,当我在我的场景中单击时,我的播放器将旋转并添加一个力并移动直到它到达我的场景中的单击点。

现在,我使用 Vectors 让它工作,并让我的玩家从一个点到另一个点。但我想修改它,这样我就可以使用物理并更好地了解我的玩家移动。就像让他加速开始移动并在他到达我的目标位置时减速

我的脚本现在看起来像这样

public GameObject isActive;
public float speed;
public Ray ray;
public Rigidbody rigidBody;



public Vector3 targetPoint;
// Use this for initialization
void Start ()
{
    targetPoint = transform.position;
}

// Update is called once per frame
void Update ()
{


}

void FixedUpdate()
{
    if (Input.GetMouseButton(0)) 
    {
        targetPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        ChangeRotationTarget ();
    }

    Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
    transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);

    rigidbody.position = Vector3.Lerp(transform.position, targetPoint, speed * Time.fixedDeltaTime);
}


void ChangeRotationTarget ()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {

        targetPoint = ray.GetPoint (hitdist);
    }

}

但是,当我运行它时,他只是从一个点滑到另一个点。无论我在刚体中施加的阻力或质量如何。

有人可以帮我做出改变吗?或者指出我正确的方向

4

2 回答 2

1

我没有时间对此进行测试,但它几乎应该是您正在寻找的。只需将您的四元数和旋转代码应用于它。

void FixedUpdate() {

    if (Input.GetMouseButton(0))
    {
        targetPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        if (rigidBody.position != targetPoint)
        {
            reachedTargetPoint = false;
            if (reachedTargetPoint == false)
            {
                GetComponent<Rigidbody>().AddForce(speed);
            }
        }

        //zoneBeforeReachingTP should be how much units before reaching targetPoint you want to start to decrease your rigidbody velocity
        if (rigidBody.position == (targetPoint - zoneBeforeReachingTP))
        {
            //speedReductionRate should be how much of speed you want to take off your rigidBody at the FixedUpdate time rate
            rigidBody.velocity = speedReductionRate;
        }
            if(rigidBody.position == targetPoint)
            {
                rigidBody.velocity = new Vector3(0, 0, 0);
                reachedTargetPoint = true;
            }
            ChangeRotationTarget();
        }  
    }
于 2016-11-26T22:57:59.580 回答
0

那是因为您修改了rigidbody.position,并且您的逻辑覆盖了物理。相反,您必须做的是对ApplyForce每个物理框架,可能使用ForceMode.Forceor ForceMode.Acceleration

于 2015-04-30T08:46:57.817 回答