-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTPBillargol.html
416 lines (340 loc) · 14.9 KB
/
TPBillargol.html
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Billargol - Mesa</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
</head>
<body>
<script>
// Crear la escena
const scene = new THREE.Scene();
//Texturas
const loader = new THREE.TextureLoader();
// Cargar texturas
const textureLoader = new THREE.TextureLoader();
const wallTexture = textureLoader.load('Wood066_1K-JPG_Color.jpg'); // Ruta de textura
//const ballTexture = textureLoader.load('Plastic013A_1K-JPG_Color.jpg');
const ballTexture = textureLoader.load('ball.jpg');
const groundTexture = textureLoader.load('fabrics_0075_color_1k.jpg');
const mushroomTexture = textureLoader.load('Plaster001_1K-JPG_Color.jpg');
// Crear la cámara
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 10, 20);
camera.lookAt(0, 0, 0);
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Crear el renderer
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Crear el campo verde (mesa)
const tableGeometry = new THREE.BoxGeometry(20, 0.5, 10); // Ancho, alto, profundidad
const tableMaterial = new THREE.MeshStandardMaterial({
map: groundTexture, // Asignar la textura al material
});
const table = new THREE.Mesh(tableGeometry, tableMaterial);
table.position.y = -0.25; // Para que quede sobre el plano XZ
scene.add(table);
// Crear un material con textura para las paredes
const wallMaterial = new THREE.MeshStandardMaterial({
map: wallTexture, // Asignar la textura al material
});
// Configuración de repetición de textura (opcional)
wallTexture.wrapS = THREE.RepeatWrapping;
wallTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set(4, 1); // Repetir la textura 4 veces en el ancho y 1 vez en la altura
const wallThickness = 0.5;
const wallHeight = 0.7;
// Paredes laterales
const wall1 = new THREE.Mesh(new THREE.BoxGeometry(20, wallHeight, wallThickness), wallMaterial);
wall1.position.set(0, wallHeight / 2, 5.25); // Lado superior
scene.add(wall1);
const wall2 = new THREE.Mesh(new THREE.BoxGeometry(20, wallHeight, wallThickness), wallMaterial);
wall2.position.set(0, wallHeight / 2, -5.25); // Lado inferior
scene.add(wall2);
// Paredes frontales
const wall3 = new THREE.Mesh(new THREE.BoxGeometry(wallThickness, wallHeight, 10), wallMaterial);
wall3.position.set(10.25, wallHeight / 2, 0); // Derecha
scene.add(wall3);
const wall4 = new THREE.Mesh(new THREE.BoxGeometry(wallThickness, wallHeight, 10), wallMaterial);
wall4.position.set(-10.25, wallHeight / 2, 0); // Izquierda
scene.add(wall4);
const limitesMesa = new THREE.Box3(
new THREE.Vector3(-9.5, 0, -4.5), // Esquina inferior izquierda
new THREE.Vector3(9.5, 1, 4.5) // Esquina superior derecha
);
function createHole(x, z) {
const holeGeometry = new THREE.CircleGeometry(0.5, 32);
const holeMaterial = new THREE.MeshPhongMaterial({ color: 0x000000 }); // Responderá a la luz
const hole = new THREE.Mesh(holeGeometry, holeMaterial);
hole.rotation.x = -Math.PI / 2;
hole.position.set(x, 0.01, z); // Elevar ligeramente
scene.add(hole);
return hole; // Retornar el agujero creado
}
// Agujero izquierdo
createHole(-9.5, 0);
// Agujero derecho
createHole(9.5, 0);
const hongos = new THREE.Group();
scene.add(hongos);
// Crear hongos y agregarlos al grupo
function createHongo(x, z) {
const hongoGeometry = new THREE.CylinderGeometry(0.2, 0.2, 1, 32);
const hongoMaterial = new THREE.MeshStandardMaterial({
map: mushroomTexture, // Asignar la textura al material
});
const hongo = new THREE.Mesh(hongoGeometry, hongoMaterial);
hongo.position.set(x, 0.5, z); // Elevarlos ligeramente sobre la mesa
hongo.boundingSphere = new THREE.Sphere(hongo.position.clone(), 0.2); // Asignar boundingSphere
hongos.add(hongo); // Agregar al grupo
}
// Distribuir hongos centrales
const hongoPositions = [
{ x: 0, z: 1 },
{ x: 0, z: 2.5 }, { x: -1, z: 0 }, { x: -2.5, z: 0 },
{ x: 0, z: -2.5 }, { x: 0, z: -1 }, { x: 2.5, z: 0 }, { x: 1, z: 0 }
];
hongoPositions.forEach(pos => createHongo(pos.x, pos.z));
// Hongos adicionales cerca de los agujeros
createHongo(-9.5, 1);
createHongo(-9.5, -1);
createHongo(9.5, 1);
createHongo(9.5, -1);
let pelota, velocidad = new THREE.Vector3(0, 0, 0);
const velocidadBase = 0.5; // Velocidad constante para el movimiento
let direccion = new THREE.Vector3();
let velocidadInicial = 0;
// Crear la pelota
function crearPelota() {
const pelotaGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const pelotaMaterial = new THREE.MeshStandardMaterial({
map: ballTexture, // Asignar la textura al material
});
pelota = new THREE.Mesh(pelotaGeometry, pelotaMaterial);
pelota.position.set(0, 0.5, 0); // Posición inicial en el centro
scene.add(pelota);
}
crearPelota();
const tacoGeometry = new THREE.CylinderGeometry(0.05, 0.1, 8, 32); // Taco delgado y largo
const tacoMaterial = new THREE.MeshStandardMaterial({
map: wallTexture, // Asignar la textura al material
});
const taco = new THREE.Mesh(tacoGeometry, tacoMaterial);
// Coloca el taco en la escena, detrás de la pelota inicialmente
tacoGeometry.rotateX(Math.PI / 2); // Alinea el cilindro en el eje Z
taco.position.set(pelota.position.x - 1, 0.1, pelota.position.z); // Cerca de la pelota
scene.add(taco);
// Detectar la posición del mouse en la escena
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
document.addEventListener('mousemove', (event) => {
// Actualiza las coordenadas del mouse
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Raycaster para encontrar el punto en la mesa
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(table);
if (intersects.length > 0) {
const point = intersects[0].point; // Punto en la mesa
// Calcula la dirección del taco
const direction = new THREE.Vector3(
point.x - pelota.position.x,
0,
point.z - pelota.position.z
).normalize();
// Coloca el taco en posición orientado hacia la pelota
const distance = 5; // Distancia del taco a la pelota
taco.position.set(
pelota.position.x - direction.x * distance,
0.5,
pelota.position.z - direction.z * distance
);
// Apunta el taco hacia la pelota
taco.lookAt(pelota.position);
}
});
// Detectar la posición del mouse en la escena
document.addEventListener('click', () => {
// Usar el raycaster para detectar el punto de clic en la mesa
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(table);
if (intersects.length > 0) {
const point = intersects[0].point;
// Dirección del golpe
const direction = new THREE.Vector3(
point.x - pelota.position.x,
0,
point.z - pelota.position.z
).normalize();
// Animación del taco
const initialPosition = taco.position.clone(); // Guarda la posición inicial
const hitPosition = new THREE.Vector3(
pelota.position.x - direction.x * 0.5,
0.1,
pelota.position.z - direction.z * 0.5
);
// Mueve el taco hacia la pelota y de vuelta
const duration = 0.5; // Duración del golpe
let progress = 0;
const animateTaco = () => {
progress += 0.1;
if (progress <= duration) {
const t = progress / duration; // Interpolación
taco.position.lerpVectors(initialPosition, hitPosition, t);
requestAnimationFrame(animateTaco);
} else {
// Regresa el taco a su posición original
taco.position.copy(initialPosition);
}
};
animateTaco();
// Aplica fuerza a la pelota
velocidad = direction.multiplyScalar(0.5); // Ajusta la velocidad del golpe
}
});
// Crear una bounding sphere para la pelota
const boundingPelota = new THREE.Sphere(pelota.position, 0.5); // Radio = 0.5
// Crear bounding spheres para los hongos
hongos.children.forEach(hongo => {
hongo.boundingSphere = new THREE.Sphere(hongo.position.clone(), 0.2); // Radio = 0.2
});
function detectarColisiones() {
// Actualizar la posición de la bounding sphere de la pelota
boundingPelota.center.copy(pelota.position);
hongos.children.forEach(hongo => {
if (hongo.boundingSphere) { // Verificar si está definida
if (boundingPelota.intersectsSphere(hongo.boundingSphere)) {
console.log('Colisión detectada con un hongo');
// Calcular el vector normal del rebote en el plano x-z
const normal = new THREE.Vector3().subVectors(pelota.position, hongo.position);
normal.y = 0; // Ignorar la componente vertical
normal.normalize();
// Reflejar la velocidad en la normal
velocidad.reflect(normal);
velocidad.y = 0; // Asegurarse de que la velocidad no tenga componente en Y
velocidad.multiplyScalar(0.98); // Reducir ligeramente la velocidad tras el rebote
// Asegurarse de que la velocidad no sea demasiado pequeña
if (Math.abs(velocidad.x) < 0.05) velocidad.x = Math.sign(velocidad.x) * 0.01;
if (Math.abs(velocidad.z) < 0.05) velocidad.z = Math.sign(velocidad.z) * 0.01;
}
}
});
}
const agujeros = []; // Array para almacenar los agujeros
// Crear agujeros y almacenarlos en el array
agujeros.push(createHole(-9.5, 0));
agujeros.push(createHole(9.5, 0));
function detectarColisionConAgujeros() {
agujeros.forEach(hole => {
const distancia = pelota.position.distanceTo(hole.position);
if (distancia < 0.6 && velocidad.length() < 0.4) { // Radio del agujero y velocidad baja
// Reiniciar posición de la pelota
pelota.position.set(0, 0.5, 0); // Posición inicial
velocidad.set(0, 0, 0); // Detener la pelota
}
});
}
// Función para mover la pelota con física
function moverPelota() {
// Aplicar la velocidad a la posición de la pelota
pelota.position.add(velocidad);
// Mantener la pelota en el plano XZ
pelota.position.y = 0.5; // Altura fija de la pelota sobre la mesa
// Rebotar contra las paredes (X y Z)
if (pelota.position.x > 9.50 || pelota.position.x < -9.50) {
velocidad.x *= -1; // Invertir la dirección X
velocidad.multiplyScalar(0.91); // Simular fricción
}
if (pelota.position.z > 4.50 || pelota.position.z < -4.50) {
velocidad.z *= -1; // Invertir la dirección Z
velocidad.multiplyScalar(0.91); // Simular fricción
}
// Aplicar fricción gradual
velocidad.multiplyScalar(0.99);
// Detener la pelota si la velocidad es muy baja
if (velocidad.length() < 0.01) {
velocidad.set(0, 0, 0);
}
}
function actualizarRotacionPelota(deltaTime) {
// Asegúrate de que las variables velocidad y pelota existan y estén inicializadas
if (!velocidad || !pelota) return;
// Velocidad angular calculada en base a la velocidad de la pelota
const velocidadMagnitud = velocidad.length();
const radioPelota = pelota.geometry.parameters.radius || 0.5; // Usa un radio por defecto si no está definido
// Factor de escala para hacer la rotación más visible
const factorEscalaRotacion = 10; // Incrementa este valor para una rotación más perceptible
const rotacionAngular = (velocidadMagnitud / radioPelota) * deltaTime * factorEscalaRotacion;
// Dirección de la rotación en función del movimiento de la pelota
const ejeRotacion = new THREE.Vector3(velocidad.z, 0, -velocidad.x).normalize();
// Aplica la rotación a la pelota
pelota.rotateOnWorldAxis(ejeRotacion, rotacionAngular);
}
// Variables para controlar el offset de la cámara
let offsetX = -5; // Posición horizontal relativa
let offsetY = 10; // Altura de la cámara
let offsetZ = 5; // Posición hacia adelante/atrás
// Listener para manejar las teclas presionadas
window.addEventListener("keydown", (event) => {
switch (event.key) {
case "ArrowUp": // Incrementar altura
offsetY += 1;
break;
case "ArrowDown": // Reducir altura
offsetY -= 1;
break;
case "ArrowLeft": // Mover la cámara a la izquierda
offsetX -= 1;
break;
case "ArrowRight": // Mover la cámara a la derecha
offsetX += 1;
break;
case "w": // Acercar la cámara
offsetZ -= 1;
break;
case "s": // Alejar la cámara
offsetZ += 1;
break;
case "h": // Generar posiciones aleatorias dentro de los límites de la mesa
const randomX = (Math.random() * 19) - 9.5; // -9.5 a 9.5
const randomZ = (Math.random() * 9) - 4.5; // -4.5 a 4.5
createHongo(randomX, randomZ);
break;
}
});
// Función para actualizar la posición de la cámara
function actualizarCamara() {
const offset = new THREE.Vector3(offsetX, offsetY, offsetZ); // Usar el offset dinámico
camera.position.copy(pelota.position.clone().add(offset)); // Seguir la pelota
camera.lookAt(pelota.position); // Enfocar siempre la pelota
}
const clock = new THREE.Clock();
// Animación principal
function animate() {
requestAnimationFrame(animate);
// Calcular deltaTime
const deltaTime = clock.getDelta(); // Tiempo en segundos desde el último frame
// Actualizar la rotación de la pelota
moverPelota(); // Mover la pelota
detectarColisiones(); // Detectar colisiones con los hongos
detectarColisionConAgujeros(); // Detectar si la pelota pasa por un agujero
actualizarCamara(); // Actualizar la cámara
actualizarRotacionPelota(deltaTime);
renderer.render(scene, camera);
}
// Luz básica
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7); // Luz ambiental
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(10, 10, 10);
scene.add(directionalLight);
animate();
</script>
</body>
</html>