简体   繁体   中英

Why isn't my 3D collision detection working?

I have several objects in my world, there are three primary types. The first is self, which is the player, the player does not move, but they do rotate. The second are bullets which fly out away from the user in a straight line. And the third are targets, these just sit somewhere and wait to be hit.

Here's the code I'm using to do collision detection and it isn't working:

        foreach (GameObject go in bullets) {
            float goRadius = go.Model.Meshes.Sum((x) => x.BoundingSphere.Radius) * go.Scale;
            EnemyObject last = null;

            Vector3 goRealPos = Vector3.Transform(go.Position, Matrix.CreateScale(go.Scale) * Matrix.CreateTranslation(go.Position) * Matrix.CreateRotationY(go.Rotation.Y));

            foreach (EnemyObject eo in targets) {
                float eoRadius = eo.Model.Meshes.Sum((x) => x.BoundingSphere.Radius) *eo.Scale;

                if (Vector3.Distance(eo.Position, goRealPos) < eoRadius + goRadius) {
                    //collision has occured
                    if (!eo.TakeHit()) {
                        last = eo;
                    }

                    //remove bullet
                    toBeRemoved.Add(go);

                    break;
                }
            }

            if (last != null) {
                targets.Remove(last);
            }
            if (go.Position.Z > 2000 || go.Position.Z < -2000) {
                toBeRemoved.Add(go);
            }
        }

Can anyone tell me why it isn't working?

Note that if the bullets are moving too fast, they might sweep through your targets without hitting them. Use sweep-through-safe hittesting technologies for example with rays.

Did you check that your calculation for goRealPos is getting approximately the coordinate you expect? Why are you transforming goRealPos from go, but not doing anything similar for eo? It could be that you are testing for collisions between object that aren't on the same coordinate system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM