# 高等向量数学¶

## 平面¶

### 到平面的距离¶

```var distance = normal.dot(point)
```

### 远离原点¶

```var point_in_plane = N*D
```

```var distance = N.dot(point) - D
```

```var distance = plane.distance_to(point)
```

```N = -N
D = -D
```

```var inverted_plane = -plane
```

### 在二维空间中构造平面¶

```var N = normal
var D = normal.dot(point)
```

```# Calculate vector from `a` to `b`.
var dvec = (point_b - point_a).normalized()
# Rotate 90 degrees.
var normal = Vector2(dvec.y, -dvec.x)
# Alternatively (depending the desired side of the normal):
# var normal = Vector2(-dvec.y, dvec.x)
```

```var N = normal
var D = normal.dot(point_a)
# this works the same
# var D = normal.dot(point_b)
```

### 平面的一些示例¶

```var inside = true
for p in planes:
# check if distance to plane is positive
if (p.distance_to(point) > 0):
inside = false
break # with one that fails, it's enough
```

```var overlapping = true

for p in planes_of_A:
var all_out = true
for v in points_of_B:
if (p.distance_to(v) < 0):
all_out = false
break

if (all_out):
# a separating plane was found
# do not continue testing
overlapping = false
break

if (overlapping):
# only do this check if no separating plane
# was found in planes of A
for p in planes_of_B:
var all_out = true
for v in points_of_A:
if (p.distance_to(v) < 0):
all_out = false
break

if (all_out):
overlapping = false
break

if (overlapping):
print("Polygons Collided!")
```

## 三维碰撞检测¶

```var overlapping = true

for p in planes_of_A:
var all_out = true
for v in points_of_B:
if (p.distance_to(v) < 0):
all_out = false
break

if (all_out):
# a separating plane was found
# do not continue testing
overlapping = false
break

if (overlapping):
# only do this check if no separating plane
# was found in planes of A
for p in planes_of_B:
var all_out = true
for v in points_of_A:
if (p.distance_to(v) < 0):
all_out = false
break

if (all_out):
overlapping = false
break

if (overlapping):
for ea in edges_of_A:
for eb in edges_of_B:
var n = ea.cross(eb)
if (n.length() == 0):
continue

var max_A = -1e20 # tiny number
var min_A = 1e20 # huge number

# we are using the dot product directly
# so we can map a maximum and minimum range
# for each polygon, then check if they
# overlap.

for v in points_of_A:
var d = n.dot(v)
max_A = max(max_A, d)
min_A = min(min_A, d)

var max_B = -1e20 # tiny number
var min_B = 1e20 # huge number

for v in points_of_B:
var d = n.dot(v)
max_B = max(max_B, d)
min_B = min(min_B, d)

if (min_A > max_B or min_B > max_A):
# not overlapping!
overlapping = false
break

if (not overlapping):
break

if (overlapping):
print("Polygons collided!")
```