I’m making a sniper game with gravity and wind influence on bullet. I’m moving bullet with constant velocity in forward direction and adding physics.gravityTime.FixedDeltatime.
So if there is a target 300 units away my bullet with take 36 frames to reach it(300/velocityTime.FixedDeltatime) which we will call predictedFrames, when i multiply predictedFrames with gravity it should give mei the y position of bullet after 36 frames but it gives me the wrong position.
I did Debug.Log(physics.gravity*Time.FixedDeltatime) and it give me -0.2 which should be the gravity per frame but it’s not, after the first frame bullet y position is 0.0011 something.
I did everything but nothing worked.
plz help
Hi @notijaz you’re really close but remember that acceleration is a change in velocity, i.e. a change in distance over time, over time. predictedFrames * Time.fixedDeltaTime represents the amount of total travel time your bullet has before it reaches the target at 300 units. The equation to calculate fall distance under acceleration is:
y_fall = 0.5 * acceleration * time * time; //this is the time over time portion for distance travelled
Check this out: Equations for a falling body - Wikipedia
And here’s some (updated) code that should work for you:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
float initial_velocity = 417f;
float distance_to_target = 300f;
float time_to_target;
int predictedFrames;
float bullet_drop;
Vector3 bulletvelocity;
// Start is called before the first frame update
void Start()
{
bulletvelocity = initial_velocity * (transform.rotation * new Vector3(1, 0, 0)); // +x velocity
Debug.Log(bulletvelocity);
time_to_target = distance_to_target / initial_velocity;
Debug.Log("Time to reach target: " + time_to_target);
predictedFrames = (int) ((distance_to_target / initial_velocity) / Time.fixedDeltaTime);
Debug.Log("Frames to reach target: " + predictedFrames);
bullet_drop = -Physics.gravity.y * 0.5f * time_to_target * time_to_target;
Debug.Log("Distance to drop: " + bullet_drop);
bullet_drop = -Physics.gravity.y * 0.5f * predictedFrames * Time.fixedDeltaTime * predictedFrames * Time.fixedDeltaTime;
Debug.Log("Distance to drop: " + bullet_drop);
Debug.Log(Physics.gravity);
}
// Update is called once per frame
void FixedUpdate()
{
bulletvelocity += Physics.gravity * Time.fixedDeltaTime;
transform.position += bulletvelocity * Time.fixedDeltaTime;
}
}