BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / util / ray.js

ray.js

fixes
timfa Tim · pushed by timfa · 4 years ago
2bbed98f History
ray.js 2.6 KiB Download Raw
1class Ray
2{
3 static Cast(scene, origin, direction, maxLength = -1)
4 {
5 direction = direction.normalize();
6 let castAngle = direction.toAngle();
7 let hits = [] // {hitObj, hitPoint}
8 for(var i = 0; i < scene.activeObjects.length; i++)
9 {
10 if(scene.activeObjects[i] != this && scene.activeObjects[i].collider.enabled)
11 {
12 var hw = scene.activeObjects[i].transform.size.x / 2;
13 var hh = scene.activeObjects[i].transform.size.y / 2;
14
15 let points =
16 [
17 new vector(scene.activeObjects[i].transform.position.x - hw, scene.activeObjects[i].transform.position.y - hh),
18 new vector(scene.activeObjects[i].transform.position.x + hw, scene.activeObjects[i].transform.position.y - hh),
19 new vector(scene.activeObjects[i].transform.position.x - hw, scene.activeObjects[i].transform.position.y + hh),
20 new vector(scene.activeObjects[i].transform.position.x + hw, scene.activeObjects[i].transform.position.y + hh)
21 ]
22
23 points.sort((p1,p2) => p1.subtract(origin).length - p2.subtract(origin).length).pop();
24
25 for(let p = 0; p < points.length; p++)
26 {
27 let point = points[p];
28 let deltaDistance = point.subtract(origin).length;
29
30 let stretched = direction.stretch(Math.min(deltaDistance, maxLength > 0? maxLength : deltaDistance))
31
32 let calcPoint = origin.add(stretched);
33
34 if(scene.activeObjects[i].collider.isInBounds(calcPoint))
35 {
36 //determine in between which vector angles ray is
37 //todo: toAngle offset if required
38 var angles = points.map(p => Ray.mapPointToPointAndAngle(p, origin)).sort();
39 castAngle < angles[1].angle ? angles.pop() : angles.shift();
40
41 //calc % of angle in relation to the angles it is between
42 let percent = castAngle / (angles[1].angle - angles[0].angle);
43
44 hits.push({hitObj: scene.activeObjects[i], hitPoint: angles[0].point.lerpTo(angles[1].point, percent)})
45
46 break;
47 }
48 }
49 }
50 }
51
52 //todo: find shortest distance
53 return hits;
54 }
55
56 static mapPointToPointAndAngle(point, origin)
57 {
58 return {
59 point: point,
60 angle: point.subtract(origin).toAngle()
61 };
62 }
63}