首页 > 解决方案 > Mathematics not working properly in unity

问题描述

I am trying to make a volleyball scene in unity. What I want is to create a scene where two NPCs are throwing the ball at each other. And I want the ball to land on random spots and the NPCs to reach the spot at the same time as the ball reaches the point. Now I am using the parabola equations to calculate where the ball should land and how much time will it take to get there. The time and the landing spot are working fine. But I can't seem to get the NPCs there at the exact time. I am using the following coroutine to move the NPC and the ball. The ball reaches the point on time but somehow the NPC reaches late.

IEnumerator playOneRound()
{

    //this is the point where the ball is going to land
    currentMovePoint.transform.position = currentRandomObjects[Random.Range(0, currentRandomObjects.Length)].transform.position;
    parabolaStartPoint.transform.position = currentStartPoint.transform.position;
    parabolaEndPoint.transform.position = currentBallPoint.transform.position;
    ballController.FollowParabola();


    //this is the time in which the ball will reach the end point of the parabola
    time = ballController.GetDuration();


    //this is the distance between the NPC and the point where the ball will land
    distance = Vector3.Distance(currentPlayer.transform.position, currentMovePoint.transform.position);
    speed = distance / time;

    // clockspeed here is the amount of seconds I am going to wait for each iteration.
    // so basically I am converting the the speed from distance-unit/second to 
    // distance-unit/clockspeed  
    distancePerClock = speed * clockSpeed;


    while (Vector3.Distance(currentPlayer.transform.position, currentMovePoint.transform.position) > 0.1f)
    {
        currentPlayer.transform.position = Vector3.MoveTowards(currentPlayer.transform.position, currentMovePoint.transform.position, distancePerClock);
        yield return new WaitForSeconds(clockSpeed);
    }
}

The math seems to be right on paper. But somehow it's not working here. Am I missing something?

标签: unity3d

解决方案


推荐阅读