@@ -21,8 +21,8 @@ SpatialHash有一个可配置的方面,它可以极大地影响其性能:单
21
21
### 使用物理系统
22
22
射线检测对于检查敌人的视线、探测实体的空间环境、快速移动的子弹等各种事情都非常有用。下面是一个从头到尾投射线条的示例,如果击中某个物体,它只会记录数据:
23
23
``` ts
24
- const hit = Physics .linecast ( start , end );
25
- if ( hit .Collider != null )
24
+ const hit = es . Physics .linecast ( start , end );
25
+ if ( hit .collider != null )
26
26
console .log ( ` ray hit ${hit }, entity: {hit.collider.entity} ` );
27
27
```
28
28
@@ -35,14 +35,14 @@ if( hit.Collider != null )
35
35
let collisionResult = null ;
36
36
37
37
// 进行检查以查看entity.getComponent(Collider)(实体上的第一个碰撞器)是否与场景中的任何其他碰撞器发生碰撞。请注意,如果您有多个碰撞器,则可以获取并遍历它们,而不是仅检查第一个碰撞器。
38
- if ( entity .getComponent (Collider ).collidesWithAny ( deltaMovement , collisionResult ) )
38
+ if ( entity .getComponent (es . Collider ).collidesWithAny ( deltaMovement , collisionResult ) )
39
39
{
40
40
// 记录CollisionResult。 您可能需要使用它来添加一些粒子效果或与您的游戏相关的任何其他内容。
41
41
console .log ( ` collision result: ${collisionResult } ` );
42
42
}
43
43
44
44
// 将实体移到新位置。 已经调整了deltaMovement为我们解决冲突。
45
- entity .position = Vector2 . add ( entity .position , deltaMovement );
45
+ entity .position = entity .position . add ( deltaMovement );
46
46
```
47
47
48
48
如果您需要对碰撞发生时的情况进行更多控制,则也可以手动检查是否与其他collider发生碰撞。 请注意,执行此操作时,deltaMovement不会为您调整。 解决冲突时,您需要考虑最小平移矢量。
@@ -51,23 +51,23 @@ entity.position = Vector2.add(entity.position, deltaMovement);
51
51
let collisionResult = null ;
52
52
53
53
// 进行检查以查看entity.getComponent<Collider>是否与一些其他Collider发生碰撞
54
- if ( entity .getComponent (Collider ).collidesWith ( someOtherCollider , deltaMovement , collisionResult ) )
54
+ if ( entity .getComponent (es . Collider ).collidesWith ( someOtherCollider , deltaMovement , collisionResult ) )
55
55
{
56
56
// 将实体移动到与命中Collider相邻的位置,然后记录CollisionResult
57
- entity .position = Vector2 . add ( entity .position , Vector2 . substract (deltaMovement , collisionResult .minimumTranslationVector ));
57
+ entity .position = entity .position . add (deltaMovement . sub ( collisionResult .minimumTranslationVector ));
58
58
console .log ( ` collision result: ${collisionResult } ` );
59
59
}
60
60
```
61
61
我们可以使用前面提到的Physics.boxcastBroadphase方法或更具体地讲,将自身排除在查询之外的版本,使上述示例更进一步。 该方法将为我们提供场景中所有在我们附近的collider,然后我们可以使用这些对撞机进行实际的碰撞检查。
62
62
63
63
``` ts
64
64
// 在我们自身以外的位置获取可能与之重叠的任何东西
65
- let neighborColliders = Physics .boxcastBroadphaseExcludingSelf ( entity .getComponent (Collider ) );
65
+ let neighborColliders = es . Physics .boxcastBroadphaseExcludingSelf ( entity .getComponent (es . Collider ) );
66
66
67
67
// 遍历并检查每个对撞机是否重叠
68
68
for ( let collider of neighborColliders )
69
69
{
70
- if ( entity .getComponent (Collider ).overlaps ( collider ) )
70
+ if ( entity .getComponent (es . Collider ).overlaps ( collider ) )
71
71
console .log ( ` 我们正在重叠一个collider : ${collider } ` );
72
72
}
73
73
```
0 commit comments