简体   繁体   English

为什么我的3D碰撞检测不起作用?

[英]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? 您是否检查过goRealPos的计算是否获得了您期望的坐标? Why are you transforming goRealPos from go, but not doing anything similar for eo? 为什么要从go转换goRealPos,但不对eo做类似的事情? It could be that you are testing for collisions between object that aren't on the same coordinate system. 可能是您正在测试不在同一坐标系上的对象之间的碰撞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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