Home > Software design >  Does a speed of an object in unity affect Destroy()?
Does a speed of an object in unity affect Destroy()?

Time:10-03

So I am making a small game in unity where you have to shoot the enemy. However, when I made the script for the bullet and enemy, it half worked and half didn't. Sometimes, the bullet would hit the enemy and destroy the enemy, however, sometimes, it would take multiple shots for it to work. But when I turn the speed of the bullet to 1 (the speed of the bullet was 500), the bullet always destroys the enemy. So this leads me to think that this has something to do with the speed of the bullet. Here is my script

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    
}
private void OnTriggerEnter(Collider other)
{
    Destroy(other.gameObject);
    Destroy(gameObject);
    Debug.Log("e");
}

For the movement of the bullet, I just used transform.Translate(Vector3.up * Time.deltaTime * speed). How can I fix this?

CodePudding user response:

The problem is not that Destroy do not work with a certain speed, the problem is that with certain speed you are not triggering the "OnTriggerEnter".

This fenomenon is called "tunneling" it happens when the object goes too fast.

That provokes that in one frame the projectile is on one side of the collider, and in the next frame is on the other side of the collider, giving the sensation like a teleport, so that's the why it do not collide, cause in any frame the engine has detected the collide.

If you're having troubles with high speed stuff, try to set your rigidbody (the one that is moving) to Interpolate, or use raycasts to fake bigger projectile colliders.

CodePudding user response:

A tricky way : bullet form A point to B point by one frame , so you can fake a point on a to b like fake point: A B/2

Point a ;
Point b ;
Update()
{
    Point ab = (a b)/2;
    bullet.point = ab;

    //check collider some .
    bullet.point = b; // set it back.
    a = b;
}

Not a good solution . but it have double hit rate.

  • Related