Skip to content

Instantly share code, notes, and snippets.

@Krxtopher
Created February 16, 2019 04:22
Show Gist options
  • Save Krxtopher/2ef02a7d33643985df966afc439a00e1 to your computer and use it in GitHub Desktop.
Save Krxtopher/2ef02a7d33643985df966afc439a00e1 to your computer and use it in GitHub Desktop.
An Amazon Sumerian script that will make the entity it is attached to orient itself smoothly so that it always faces another entity.
'use strict';
/**
* This script will make the entity it is attached to orient itself smoothly so that it always
* faces the entity assigned to the `lookAtEntity` script parameter.
*/
function setup(args, ctx) {
// The point to focus on, expressed in world space.
ctx.entityData.focusPoint = args.lookAtEntity.transformComponent.getWorldTranslation();
lookAtWorldPoint(ctx.entity, ctx.entityData.focusPoint);
}
function update(args, ctx) {
const newFocusPoint = args.lookAtEntity.transformComponent.getWorldTranslation();
const oldFocusPoint = ctx.entityData.focusPoint;
let focusPoint;
if (args.smoothing <= 0) {
focusPoint = newFocusPoint;
} else {
const frameTime = ctx.world.tpf;
focusPoint = ctx.entityData.focusPoint = oldFocusPoint.clone().lerp(newFocusPoint, frameTime / args.smoothing);
}
lookAtWorldPoint(ctx.entity, focusPoint);
// Store the current focus point for use in later smoothing interpolation.
ctx.entityData.focusPoint = focusPoint;
}
/**
* Orients an entity to face the specified point in world space.
*/
function lookAtWorldPoint(entity, worldPoint) {
let parentEntity = entity.parent().first();
let point = parentEntity ? worldPointToLocal(worldPoint, parentEntity) : worldPoint;
entity.lookAt(point);
}
/**
* Converts a point expressed in world space to a point expressed in the entity's local space.
*/
function worldPointToLocal(point, entity) {
let invertedWorld = entity.transformComponent.worldTransform.clone().invert();
let out_point = new sumerian.Vector3();
invertedWorld.applyForward(point, out_point);
return out_point;
}
var parameters = [
{
key: "lookAtEntity",
type: "entity",
default: null,
description: "The entity to look at."
},
{
key: "smoothing",
type: "float",
default: 0.4,
description: "The amount of smoothing to apply to tracking."
}
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment