|
<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<meta charset="utf-8"> |
|
<title>Aframe and Three.js Keyboard Interaction Demo</title> |
|
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> |
|
<script src="https://threejs.org/build/three.js"></script> |
|
</head> |
|
<body> |
|
<a-scene keyboard-shortcuts> |
|
<a-entity position="0 1.6 0"> |
|
<a-entity id="camera" camera look-controls wasd-controls></a-entity> |
|
</a-entity> |
|
<a-sky color="#0000ff"></a-sky> |
|
<a-entity id="objectsContainer"></a-entity> |
|
</a-scene> |
|
|
|
<script> |
|
AFRAME.registerComponent('keyboard-shortcuts', { |
|
init: function () { |
|
window.addEventListener('keydown', (event) => { |
|
const key = event.key.toLowerCase(); |
|
if (key.length === 1 && /^[a-z]+$/.test(key)) { |
|
this.generateObject(key); |
|
} |
|
}); |
|
}, |
|
|
|
generateObject: function (key) { |
|
const objectsContainer = document.querySelector('#objectsContainer'); |
|
const object = document.createElement('a-entity'); |
|
|
|
|
|
object.setAttribute('geometry', { |
|
primitive: 'box', |
|
width: 1, |
|
height: 1, |
|
depth: 1 |
|
}); |
|
object.setAttribute('material', { color: getRandomColor() }); |
|
object.setAttribute('position', getRandomPosition()); |
|
|
|
objectsContainer.appendChild(object); |
|
} |
|
}); |
|
|
|
|
|
function getRandomColor() { |
|
const letters = '0123456789ABCDEF'; |
|
let color = '#'; |
|
for (let i = 0; i < 6; i++) { |
|
color += letters[Math.floor(Math.random() * 16)]; |
|
} |
|
return color; |
|
} |
|
|
|
|
|
function getRandomPosition() { |
|
const x = Math.random() * 10 - 5; |
|
const y = Math.random() * 10 - 5; |
|
const z = Math.random() * 10 - 5; |
|
return `${x} ${y} ${z}`; |
|
} |
|
</script> |
|
</body> |
|
</html> |