Home>

The task is to implement the movement of the cube by jumping strictly at a fixed length, so that it moves only along integer coordinates. It was implemented by calculating the velocity vector of a ballistic trajectory with a given angle and distance (in the example -45 ° and 2 distance units), followed by decomposition into vectors in X, Y and assignment to rigidbody.velocity. The problem is that the values ​​obtained by the formula on paper clearly coincide with the required ones, but the new position of the object in Unity is slightly different from the required one, knocking down integer coordinates. Moving an object in Unity tends to 2 with decreasing Fixed TimeStep, but also remains not intact. What is the reason for this discrepancy?

void Update(){
 ...
 if(touch.phase== TouchPhase.Ended)  //обработка свайпов и выбор направления прыжка
  {
        directionChosen= true;
        if (swipe.magnitude < min_swipe_distance)
             return;
        if(Mathf.Abs(swipe.x)> Mathf.Abs(swipe.y)) //Horizontal Swipe
          {
            if (swipe.x > 0) {             //Right
                    Debug.Log("right");
                    fromTo= new Vector3(0.0f, 0.0f, -1.0f);
                } else {                   //Left
                    Debug.Log("left");
                    fromTo= new Vector3(0.0f, 0.0f, 1.0f);
                  }
             } else {                           //Vertical swipe
                    if (swipe.y > 0) {      //Up
                        Debug.Log("up");
                        fromTo= new Vector3(1.0f, 0.0f, 0.0f);
                    } else {                //Down
                        Debug.Log("down");
                        fromTo= new Vector3(-1.0f, 0.0f, 0.0f);
                    }
  }
    ...
}
void FixedUpdate() {
   if(directionChosen) {
         float x;
            if(fromTo.x== 0)  {
               x= fromTo.z*jumpDistance;  //
            } else {                       //Перемещение по X
               x= fromTo.x*jumpDistance;  //
            }
         float y= fromTo.y;     //Перемещение по Y
         float Angle= 45*Mathf.PI /180;  //Перевод 45 градусов в радианы
         float v2= (g * x*x)/(2*(y -Mathf.Tan(Angle) * x )*Mathf.Pow(Mathf.Cos(Angle), 2));  //Квадрат необходимой скорости
         float v= Mathf.Sqrt(Mathf.Abs(v2));   //Извлечение корня
         rb.velocity= new Vector3(fromTo.x*v*Mathf.Cos(Angle), v*Mathf.Sin(Angle), fromTo.z*v*Mathf.Cos(Angle)); //Задание вектора скорости по базовым векторам
         directionChosen= false;
    }
 }

Could you format the code to make it easier to read? (example)

aepot2021-12-30 12:24:11