Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PrismarineJS
GitHub Repository: PrismarineJS/mineflayer
Path: blob/master/lib/plugins/ray_trace.js
1467 views
1
const { Vec3 } = require('vec3')
2
const { RaycastIterator } = require('prismarine-world').iterators
3
4
module.exports = (bot) => {
5
function getViewDirection (pitch, yaw) {
6
const csPitch = Math.cos(pitch)
7
const snPitch = Math.sin(pitch)
8
const csYaw = Math.cos(yaw)
9
const snYaw = Math.sin(yaw)
10
return new Vec3(-snYaw * csPitch, snPitch, -csYaw * csPitch)
11
}
12
13
bot.blockInSight = (maxSteps = 256, vectorLength = 5 / 16) => {
14
const block = bot.blockAtCursor(maxSteps * vectorLength)
15
if (block) return block
16
}
17
18
bot.blockAtCursor = (maxDistance = 256, matcher = null) => {
19
return bot.blockAtEntityCursor(bot.entity, maxDistance, matcher)
20
}
21
22
bot.entityAtCursor = (maxDistance = 3.5) => {
23
const block = bot.blockAtCursor(maxDistance)
24
maxDistance = block?.intersect.distanceTo(bot.entity.position) ?? maxDistance
25
26
const entities = Object.values(bot.entities)
27
.filter(entity => entity.type !== 'object' && entity.username !== bot.username && entity.position.distanceTo(bot.entity.position) <= maxDistance)
28
29
const dir = new Vec3(-Math.sin(bot.entity.yaw) * Math.cos(bot.entity.pitch), Math.sin(bot.entity.pitch), -Math.cos(bot.entity.yaw) * Math.cos(bot.entity.pitch))
30
const iterator = new RaycastIterator(bot.entity.position.offset(0, bot.entity.eyeHeight, 0), dir.normalize(), maxDistance)
31
32
let targetEntity = null
33
let targetDist = maxDistance
34
35
for (let i = 0; i < entities.length; i++) {
36
const entity = entities[i]
37
const w = entity.width / 2
38
39
const shapes = [[-w, 0, -w, w, entity.height, w]]
40
const intersect = iterator.intersect(shapes, entity.position)
41
if (intersect) {
42
const entityDir = entity.position.minus(bot.entity.position) // Can be combined into 1 line
43
const sign = Math.sign(entityDir.dot(dir))
44
if (sign !== -1) {
45
const dist = bot.entity.position.distanceTo(intersect.pos)
46
if (dist < targetDist) {
47
targetEntity = entity
48
targetDist = dist
49
}
50
}
51
}
52
}
53
54
return targetEntity
55
}
56
57
bot.blockAtEntityCursor = (entity = bot.entity, maxDistance = 256, matcher = null) => {
58
if (!entity.position || !entity.height || !entity.pitch || !entity.yaw) return null
59
const { position, height, pitch, yaw } = entity
60
61
const eyePosition = position.offset(0, height, 0)
62
const viewDirection = getViewDirection(pitch, yaw)
63
64
return bot.world.raycast(eyePosition, viewDirection, maxDistance, matcher)
65
}
66
}
67
68