I moved some things around in the rewritten script and got things sort of working. I no longer get undefined errors, and only the closest enemy is moved on key press. The only abnormality is that while the rotation works upon look, it quickly accelerates out of control. Here is the updated script:
var EntitiesInView = pc.createScript("entitiesInView");
// initialize code called once per entity
EntitiesInView.prototype.initialize = function() {
this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown, this);
};
this.vec = new pc.Vec3();
this.visibleEnemies = [];
var closestEnemy;
// update code called every frame
EntitiesInView.prototype.update = function(dt) {
var projectionMatrix = this.entity.camera.projectionMatrix;
var viewMatrix = this.entity.camera.viewMatrix;
var frustum = new pc.Frustum(projectionMatrix, viewMatrix);
var enemies = this.app.root.findByTag("enemy");
var cameraPos = this.entity.getPosition();
enemies.forEach(function(enemy) {
enemy.model.model.meshInstances.forEach(function(meshInstance) {
var enemyPos = enemy.getPosition();
if (frustum.containsPoint(enemyPos) === true) {
this.visibleEnemies.push(enemy);
}
var minDistance = 5;
var shortest = Infinity;
visibleEnemies.forEach(function(visible_enemy) {
this.vec.copy(visible_enemy.getPosition());
var distance = this.vec.distance(cameraPos);
if (distance <= shortest && distance <= minDistance) {
shortest = distance;
closestEnemy = visible_enemy;
closestEnemy.rotate(0, 0.01, 0);
}
});
});
});
};
EntitiesInView.prototype.onKeyDown = function(event) {
// Check event.key to detect which key has been pressed
if (this.app.keyboard.wasPressed(pc.KEY_Y)) {
if (closestEnemy) {
closestEnemy.translate(0, 0.1, 0);
}
}
};