diff --git a/lib/cursor.js b/lib/cursor.js index 9f94bdbd..c5db2e5a 100644 --- a/lib/cursor.js +++ b/lib/cursor.js @@ -2,6 +2,14 @@ const { Vec3 } = require('vec3') +function getViewDirection (pitch, yaw) { + const csPitch = Math.cos(pitch) + const snPitch = Math.sin(pitch) + const csYaw = Math.cos(yaw) + const snYaw = Math.sin(yaw) + return new Vec3(-snYaw * csPitch, snPitch, -csYaw * csPitch) +} + class Cursor { constructor (viewer, renderer, bot) { // Init state @@ -37,9 +45,36 @@ class Cursor { document.addEventListener('mouseup', (e) => { this.buttons[e.button] = false }) + document.addEventListener('mousedown', (e) => { if (document.pointerLockElement !== renderer.domElement) return this.buttons[e.button] = true + + const entity = bot.nearestEntity((e) => { + if (e.position.distanceTo(bot.entity.position) <= (bot.player.gamemode === 1 ? 5 : 3)) { + const dir = getViewDirection(bot.entity.pitch, bot.entity.yaw) + const { width, height } = e + const { x: eX, y: eY, z: eZ } = e.position + const { x: bX, y: bY, z: bZ } = bot.entity.position + const box = new THREE.Box3( + new THREE.Vector3(eX - width / 2, eY, eZ - width / 2), + new THREE.Vector3(eX + width / 2, eY + height, eZ + width / 2) + ) + + const r = new THREE.Raycaster( + new THREE.Vector3(bX, bY + 1.52, bZ), + new THREE.Vector3(dir.x, dir.y, dir.z) + ) + const int = r.ray.intersectBox(box, new THREE.Vector3(eX, eY, eZ)) + return int !== null + } + + return false + }) + + if (entity) { + bot.attack(entity) + } }) this.lastPlaced = 4 // ticks since last placed bot.on('physicsTick', () => { if (this.lastPlaced < 4) this.lastPlaced++ })