I am currently developing a baseball game with Unity.
I need to know the sophisticated drop point to implement baseball defense.
private void Movement()
{
Vector3 hitDirection = Quaternion.Euler(0f, 0f, 0f) * hitter.transform.forward;
ballRigidbody.useGravity = true;
ballRigidbody.AddForce(hitDirection * 3000);
ballRigidbody.AddForce(Vector3.up * 10, ForceMode.Impulse);
StartCoroutine(StopBall(ballRigidbody));
}
IEnumerator StopBall(Rigidbody ballRigidbody)
{
yield return new WaitForSeconds(1f);
if (ballRigidbody.gameObject != null)
{
ballRigidbody.velocity *= 0.5f;
if (ballRigidbody.velocity.magnitude > 0)
StartCoroutine(StopBall(ballRigidbody));
}
}
The above code is an example of a code that makes the ball move.
private Vector3 PredictBallPosition(Vector3 initialPosition, Vector3 initialVelocity)
{
Vector3 position = initialPosition;
Vector3 velocity = initialVelocity;
for (float t = 0; t < maxSimulationTime; t += timeStep)
{
position += velocity * timeStep;
}
return position;
}
I simply tried to solve it through a for, but I couldn’t find the exact drop point.
In another way, I implemented the parabola myself and moved it, but I gave up because the trajectory I wanted didn’t come out.
Is there a good way to know the drop point of the ball?
AddForce(3000) will get scaled by deltatime, making you apply a different amount of force each time. Rigidbodies support drag and friction, so I don’t know why implement it yourself and by applying it only once a second it becomes not like true physics, so no physical formula for movement will help you. That prediction for loop of yours doesn’t account for friction. And lastly, invoking coroutines recursively like that is awful for memory use. Just use a while loop.
Why dont you just apply a force to the ball when the bat hits it and let unity physics engine do the rest?This way you can compute the ball direction and speed, from the position in 2 consecutive frames, and use this to get the landing position of the ball: discussions.unity.com/t/…