Why isn't my 3D collision detection working?

本秂侑毒 提交于 2019-12-23 05:38:05

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5291667/why-isnt-my-3d-collision-detection-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!