Physics: Implemented SimpleNarrowPhase, a narrow phase that supports discrete collisi...
[kong.git] / src / net / habraun / kong / physics / SimpleNarrowPhase.scala
blobaa2349f373e35ef5ded9319be0c4a858b6ffd5a0
1 /*
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)))
35 else {
36 None
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)))
47 else {
48 None
54 private[this] def circleLineSegment(b1: Body, b2: Body, circle: Circle, lineSegment: LineSegment):
55 Option[Collision] = {
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
64 val b = m * d
65 val c = (m * m) - circle.radius * circle.radius
66 val dis = b * b - c
67 if (dis >= 0) {
68 val t1 = -b + Math.sqrt(dis)
69 val t2 = -b - Math.sqrt(dis)
70 if (t2 >= 0 && t1 <= tmax) {
71 val cp = b1.position
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)))
78 else {
79 None
82 else {
83 None