Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add entityAtCursor function #2077

Merged
merged 11 commits into from
Aug 7, 2022
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
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
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
}
}