Bình thường cảnh render của ta chưa có thể điều khiển tùy chỉnh nó được, bài nay sẽ giới thiệu đến các bạn dat.GUI, thư viện tạo giao diện người dùng dễ dàng.
Mã nguồn ở đây: http://code.google.com/p/dat-gui/
Ở đây ta sẽ sử dụng dat.GUI để thêm giao diện người dùng cho ví dụ ở bài 8 để làm những việc sau:
- Kiểm soát tốc độ nảy của quả bóng
- Kiểm soát tốc độ quay của khối vuông
Cdn miễn phí:
https://res.cloudinary.com/lamnguyencdn/raw/upload/v1637203550/ThreeJsUntils/dat.gui.js
Chúng ta bắt đầu. Chúng ta sẽ đình nghĩa 1 control
var controls = new function() {
this.rotationSpeed = 0.02; //Tốc độ quay
this.bouncingSpeed = 0.03; //Tốc độ nảy
}
Theo vào GUI
var gui = new dat.GUI();
gui.add(controls, 'rotationSpeed', 0, 0.5);
gui.add(controls, 'bouncingSpeed', 0, 0.5);
Khi render ta sử dụng thuộc tính của Control
cube.rotation.x += controls.rotationSpeed;
cube.rotation.y += controls.rotationSpeed;
cube.rotation.z += controls.rotationSpeed;
step += controls.bouncingSpeed;
Giờ ta sẽ dùng Control cho camera, Giúp phóng to, thu nhỏ và xoay Camera theo đối tượng
Lăn bi chuột để phóng to, thu nhỏ, Kéo thả chuột để xoay
var clock = new THREE.Clock();
var trackballControls = new THREE.TrackballControls(
camera,
renderer.domElement
);
trackballControls.rotateSpeed = 1.0;
trackballControls.zoomSpeed = 1.2;
trackballControls.panSpeed = 0.8;
trackballControls.noZoom = false;
trackballControls.noPan = false;
trackballControls.staticMoving = true;
trackballControls.dynamicDampingFactor = 0.3;
trackballControls.keys = [65, 83, 68];
Nếu bạn nhấn S khi di chuyển chuột, bạn có thể phóng to và thu nhỏ, và nếu bạn nhấn D, bạn có thể quay xung quanh cảnh.
Xem thử
Tự động thay đổi kích thước render khi kích thước trình duyệt thay đổi
Thêm code sau vào mã html
window.addEventListener('resize', onResize, false);
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}