2 Copyright (c) 2009 Hanno Braun <hanno@habraun.net>
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
19 package net
.habraun
.kong
.physics
23 class SimpleNarrowPhase
extends NarrowPhase
{
25 def inspectCollision(b1
: Body
, b2
: Body
) = {
26 if (b1
.shape
.isInstanceOf
[Circle
] && b2
.shape
.isInstanceOf
[Circle
]) {
27 val circle1
= b1
.shape
.asInstanceOf
[Circle
]
28 val circle2
= b2
.shape
.asInstanceOf
[Circle
]
29 val dSquared
= (b1
.position
- b2
.position
).squaredLength
30 if (dSquared
<= circle1
.radius
+ circle2
.radius
) {
31 val normal1
= (b2
.position
- b1
.position
).normalize
32 val normal2
= (b1
.position
- b2
.position
).normalize
33 Some(Collision(b1
, b2
, normal1
, normal2
, Vec2D(0, 0)))
39 else if (b1
.shape
.isInstanceOf
[Circle
] && b2
.shape
.isInstanceOf
[LineSegment
]) {
40 circleLineSegment(b1
, b2
, b1
.shape
.asInstanceOf
[Circle
], b2
.shape
.asInstanceOf
[LineSegment
])
42 else if (b1
.shape
.isInstanceOf
[LineSegment
] && b2
.shape
.isInstanceOf
[Circle
]) {
43 val collision
= circleLineSegment(b2
, b1
, b2
.shape
.asInstanceOf
[Circle
],
44 b1
.shape
.asInstanceOf
[LineSegment
]).getOrElse
{ throw new AssertionError
}
45 Some(Collision(b1
, b2
, collision
.normal2
, collision
.normal1
, Vec2D(0, 0)))
54 private[this] def circleLineSegment(b1
: Body
, b2
: Body
, circle
: Circle
, lineSegment
: LineSegment
):
56 val circle
= b1
.shape
.asInstanceOf
[Circle
]
57 val lineSegment
= b2
.shape
.asInstanceOf
[LineSegment
]
59 val p
= b2
.position
+ lineSegment
.p1
60 val d
= (lineSegment
.p2
- lineSegment
.p1
).normalize
61 val tmax
= (lineSegment
.p2
- lineSegment
.p1
).length
63 val m
= p
- b1
.position
65 val c
= (m
* m
) - circle
.radius
* circle
.radius
68 val t1
= -b
+ Math
.sqrt(dis
)
69 val t2
= -b
- Math
.sqrt(dis
)
70 if (t2
>= 0 && t1
<= tmax
) {
72 val v
= lineSegment
.p2
- lineSegment
.p1
73 val t
= -(((p
.x
- cp
.x
) * v
.x
) + ((p
.y
- cp
.y
) * v
.y
)) / ((d
.x
* v
.x
) + (d
.y
* v
.y
))
74 val normal1
= (p
+ (d
* t
)).normalize
75 val normal2
= normal1
.inverse
76 Some(Collision(b1
, b2
, normal1
, normal2
, Vec2D(0, 0)))