Skip to content
Merged
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions lib/plugins/ray_trace.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { Vec3 } = require('vec3')
const { RaycastIterator } = require('prismarine-world').iterators

module.exports = (bot) => {
function getViewDirection (pitch, yaw) {
Expand All @@ -23,4 +24,39 @@ module.exports = (bot) => {

return bot.world.raycast(eyePosition, viewDirection, maxDistance, matcher)
}

bot.entityAtCursor = (maxDistance = 3.5) => {
const block = bot.blockAtCursor(maxDistance)
maxDistance = block?.intersect.distanceTo(bot.entity.position) ?? maxDistance

const entities = Object.values(bot.entities)
.filter(entity => entity.type !== 'object' && entity.username !== bot.username && entity.position.distanceTo(bot.entity.position) <= maxDistance)

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))
const iterator = new RaycastIterator(bot.entity.position.offset(0, bot.entity.height, 0), dir.normalize(), maxDistance)

let targetEntity = null
let targetDist = maxDistance

for (let i = 0; i < entities.length; i++) {
const entity = entities[i]
const w = entity.width / 2

const shapes = [[-w, 0, -w, w, entity.height + (entity.type === 'player' ? 0.18 : 0), w]]
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where does the 0.18 constant come from?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding the 0.18 constant comes is due to this where the bot's height is set to its eye height, 1.62, rather than the bot's actual height 1.80.

const intersect = iterator.intersect(shapes, entity.position)
if (intersect) {
const entityDir = entity.position.minus(bot.entity.position) // Can be combined into 1 line
const sign = Math.sign(entityDir.dot(dir))
if (sign !== -1) {
const dist = bot.entity.position.distanceTo(intersect.pos)
if (dist < targetDist) {
targetEntity = entity
targetDist = dist
}
}
}
}

return targetEntity
}
}