05-09 18:17
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[WebGL] Collision Detection 본문

Programming/WebGL(ThreeJS)

[WebGL] Collision Detection

cinema4dr12 2015. 8. 7. 21:32

이번 예제는 충돌을 감지와 관련된 것이다. 컨트롤하는 오브젝트가 다른 오브젝트와 충돌 시 상단에 충돌했다는 메시지를 표시하도록 하였습니다.


* NOTE: FULL SCREEN MODE로 실행해야 제대로 컨트롤 할 수 있습니다.

Download Project

10-01-collision-detection.zip


Click here to view with full screen mode


Operations

Mouse Left Button Click & Drag: Camera Rotating

Mouse Wheel: Camera Zoom In & Out

Mouse Right Button Click & Drag: Camera Panning

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// standard global variables
var container, scene, camera, renderer, controls, stats;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
 
// custom global variables
var MovingCube;
var collidableMeshList = [];
 
var arrowList = [];
var directionList = [];
 
init();
animate();
 
// FUNCTIONS
function init()
{
    // SCENE
    scene = new THREE.Scene();
 
    // CAMERA
    var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
    var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
    camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
    scene.add(camera);
    camera.position.set(0,150,400);
    camera.lookAt(scene.position);
 
    // RENDERER
    if ( Detector.webgl )
        renderer = new THREE.WebGLRenderer( {antialias:true} );
    else
        renderer = new THREE.CanvasRenderer();
    renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    container = document.getElementById'ThreeJS' );
    container.appendChild( renderer.domElement );
 
    // EVENTS
    THREEx.WindowResize(renderer, camera);
    THREEx.FullScreen.bindKey({ charCode : 'f'.charCodeAt(0) });
 
    // CONTROLS
    controls = new THREE.OrbitControls( camera, renderer.domElement );
 
    // STATS
    stats = new Stats();
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom = '0px';
    stats.domElement.style.zIndex = 100;
    container.appendChild( stats.domElement );
 
    // LIGHT
    var light = new THREE.PointLight(0xffffff);
    light.position.set(0,250,0);
    scene.add(light);
 
    // FLOOR
    var floorTexture = new THREE.ImageUtils.loadTexture( 'img/Wood_floor.jpg' );
    floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping; 
    floorTexture.repeat.set( 11 );
    var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
    var floorGeometry = new THREE.PlaneGeometry(100010001010);
    var floor = new THREE.Mesh(floorGeometry, floorMaterial);
    floor.position.y = -0.5;
    floor.rotation.x = Math.PI / 2;
    scene.add(floor);
 
    // SKYBOX/FOG
    var skyBoxGeometry = new THREE.CubeGeometry( 100001000010000 );
    var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x9999ff, side: THREE.BackSide } );
    var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
    scene.add(skyBox);
    
    ////////////
    // CUSTOM //
    ////////////
    // Make MovingCube that is controllable
    var cubeGeometry = new THREE.CubeGeometry( 505050888 );
    var wireMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe:true } );
    MovingCube = new THREE.Mesh( cubeGeometry, wireMaterial );
    MovingCube.position.set(025.10);
    scene.add( MovingCube );
    
    // Geometry, BasicMaterial, WireMaterial for wall & wall2
    var wallGeometry = new THREE.CubeGeometry( 10010020888 );
    var wallMaterial = new THREE.MeshBasicMaterial( {color: 0xef1d76} );
    var wireMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe:true } );
    
    // Make "wall1" & push it into colliableMeshList with which MovingCube can collide
    var wall = new THREE.Mesh(wallGeometry, wallMaterial);
    wall.position.set(10050-100);
    scene.add(wall);
    collidableMeshList.push(wall);
    var wall = new THREE.Mesh(wallGeometry, wireMaterial);
    wall.position.set(10050-100);
    scene.add(wall);
 
    // Geometry, BasicMaterial, WireMaterial for sphere
    var sphereGeometry = new THREE.SphereGeometry( 254040 );
    var sphereMaterial = new THREE.MeshBasicMaterial( {color: 0x58ef1d} );
 
    // Make "sphere" & push it into colliableMeshList with which MovingCube can collide
    var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
    sphere.position.set(10025200);
    scene.add(sphere);
    collidableMeshList.push(sphere);
    var sphere = new THREE.Mesh(sphereGeometry, wireMaterial);
    sphere.position.set(10025200);
    scene.add(sphere);
 
    // Geometry, BasicMaterial, WireMaterial for cylinder
    var cylinderGeometry = new THREE.CylinderGeometry( 2525804040 );
    var cylinderMaterial = new THREE.MeshBasicMaterial( {color: 0xfcb678} );
 
    // Make "cylinder" & push it into colliableMeshList with which MovingCube can collide
    var cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial);
    cylinder.position.set(-10040150);
    scene.add(cylinder);
    collidableMeshList.push(cylinder);
    var cylinder = new THREE.Mesh(cylinderGeometry, wireMaterial);
    cylinder.position.set(-10040150);
    scene.add(cylinder);
}
 
function clearText()
{
    document.getElementById('message').innerHTML = '..........';
}
 
function appendText(txt)
{
    document.getElementById('message').innerHTML += txt;
}
 
function animate()
{
    requestAnimationFrame( animate );
    render();        
    update();
}
 
function update()
{
    var delta = clock.getDelta(); // seconds.
    var moveDistance = 200 * delta; // 200 pixels per second
    var rotateAngle = Math.PI / 2 * delta;   // pi/2 radians (90 degrees) per second
    
    if ( keyboard.pressed("A") )
        MovingCube.rotation.y += rotateAngle;
    if ( keyboard.pressed("D") )
        MovingCube.rotation.y -= rotateAngle;
            
    if ( keyboard.pressed("left") )
        MovingCube.position.x -= moveDistance;
    if ( keyboard.pressed("right") )
        MovingCube.position.x += moveDistance;
    if ( keyboard.pressed("up") )
        MovingCube.position.z -= moveDistance;
    if ( keyboard.pressed("down") )
        MovingCube.position.z += moveDistance;
                
    // origin point of MovingCube in global coordinate
    var originPoint = MovingCube.position.clone();
 
    clearText();
    
    // collision detection
    for (var vertexIndex = 0; vertexIndex < MovingCube.geometry.vertices.length; vertexIndex++)
    {        
        var localVertex = MovingCube.geometry.vertices[vertexIndex].clone();
        var globalVertex = localVertex.applyMatrix4( MovingCube.matrix );
        var directionVector = globalVertex.sub( MovingCube.position );
        
        var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
        var collisionResults = ray.intersectObjects( collidableMeshList );
        if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
            appendText(" Hit ");
    }
 
    controls.update();
    stats.update();
}
 
function render()
{
    renderer.render( scene, camera );
}
cs


'Programming > WebGL(ThreeJS)' 카테고리의 다른 글

[WebGL] Leap Motion 1  (0) 2015.08.07
[WebGL] PhysiJS Freefall  (0) 2015.08.07
[WebGL] Viewport 4분할  (0) 2015.08.07
[WebGL] Model Animation Control  (0) 2015.08.07
[WebGL] Tween Animation  (0) 2015.08.07
Comments