# Why does this code not work?

Essentially I am try to make a ball “jump”, but without using physics because the ball has to travel a certain distance each time it jumps. Move() is called in update. JumpPosition is just the current position of the ball on a plane. EndJumpPosition is given to this script by another script.

``````private void Move()
{
if (isJump)
{
jumpPosition = new Vector2(transform.position.x , transform.position.z);

if (Mathf.Abs(jumpPosition.magnitude) < Mathf.Abs(endJumpPosition.magnitude) / 2)
{
Debug.Log("HalwayThere");
transform.Translate(new Vector3(0 , 0.05f , 0));
}
else
{
transform.Translate(new Vector3(0 , -0.05f , 0));
}
}

transform.Translate(new Vector3(0 , 0 , speed));
}
``````

I am trying to get the ball to move up halfway, then move back down once it passed halfway. I am using the magnitude because the ball’s and endJumpPosition’s rotations are altered. The “HalfwayThere” appears in the console once, and then the ball just keeps going down.

Your problem is most likely the whole comparison in the if condition, because it doesn’t really tell anything. if your player is at (10000, 0, 0) and endJumpPosition is at (10002, 0, 0) you well never be smaller than half of endPosition as he would need o move to a position smaller than 5001 on the x-Axis.

Additionally, you are never setting isJump to false, thus he always executes on side of the if-condition.

You need to store your start jump position and compare your currentToEnd distance to the startToEnd distance. On this way you are only looking at vectors that represent the distance you want to jump.

``````bool _IsJump;
Vector2 _StartJumpPosition;
Vector2 _EndJumpPosition;
private void Jump()
{
if(Input.GetKey(KeyCode.Space))
{
_IsJump = true;
_StartJumpPosition = new Vector2(transform.position.x, transform.position.z);
}
}

private void Move()
{
if (_IsJump)
{
Vector2 currentJumpPosition = new Vector2(transform.position.x, transform.position.z);
Vector2 startToEnd = _EndJumpPosition - _StartJumpPosition;
Vector2 startToCurrent = currentJumpPosition - _StartJumpPosition ;

float startToEndDist = startToEnd.magnitude;
float startToCurrentDist = startToEnd.magnitude;

// is the distance to the start smaller than the distance to the end
if (startToCurrentDist < startToEndDist / 2)
{
Debug.Log("HalwayThere");
transform.Translate(new Vector3(0, 0.05f, 0));
}
else
{
transform.Translate(new Vector3(0, -0.05f, 0));
// did we move further than the end point
if(startToCurrentDist >= startToEndDist)
{
_IsJump = false;
transform.position = new Vector3(_EndJumpPosition.x, 0.0f, _EndJumpPosition.y);
}
}
}
transform.Translate(new Vector3(0, 0, speed));
}
``````

Something along those lines should do it if I understood the situation correct.