I’m currently working on a project where I’m trying to achieve step-by-step lerp animation using the TweenPosition
script and a JSON file with coordinate data. The goal is to smoothly transition the entity from one coordinate to the next in a sequence.
I’ve implemented the following code:
var TweenPosition = pc.createScript(‘tweenPosition’);
//Attached JSON file from asset
TweenPosition.attributes.add(‘jsonAsset’, { type: ‘asset’, assetType: ‘json’ });
TweenPosition.attributes.add(‘duration’, { type: ‘number’, default: 100 });
TweenPosition.attributes.add(‘easing’, { type: ‘string’, default: ‘Linear’ });
TweenPosition.attributes.add(‘delay’, { type: ‘number’, default: 2 });
TweenPosition.attributes.add(‘loop’, { type: ‘boolean’, default: true });
TweenPosition.attributes.add(‘yoyo’, { type: ‘boolean’, default: false });
TweenPosition.attributes.add(‘repeat’, { type: ‘number’, default: 2 });
TweenPosition.prototype.initialize = function () {
// create our tween
this.reset();
// handle attribute changes
this.on('attr:duration', function (value) {
this.tween.duration = value;
}, this);
this.on('attr:easing', this.reset, this);
this.on('attr:delay', this.reset, this);
this.on('attr:loop', this.reset, this);
this.on('attr:yoyo', this.reset, this);
this.on('attr:repeat', this.reset, this);
};
TweenPosition.prototype.reset = function () {
// Get JSON data from a project asset
var characterData = this.jsonAsset.resource;
console.log(characterData)
// if we are already tweening then stop first
if (this.tween) {
this.tween.stop();
}
// reset our position
this.entity.setLocalPosition(-10, 0, 0);
if (this.jsonAsset && this.jsonAsset.resource) {
var ballPosition = this.jsonAsset.resource.ballLocations;
// Convert coordinates from centimeters to meters
var convertToMeters = function(coord) {
return coord / 100; // 1 cm = 0.01 m
}
// Create a new tween to animate through the coordinates
var tween = this.entity.tween(this.entity.getLocalPosition());
for (var i = 0; i < ballPosition.length; i++) {
var coords = ballPosition[i];
var destination = new pc.Vec3(
convertToMeters(coords.x),
convertToMeters(coords.y),
convertToMeters(coords.z)
);
tween = tween.to(destination, this.duration, pc[this.easing])
.delay(this.delay);
}
// Configure loop and yoyo
tween = tween.loop(this.loop)
.yoyo(this.yoyo);
// Only set repeats if loop is false
if (!this.loop) {
tween = tween.repeat(this.repeat);
}
// Start the tween
tween.start();
}
};
the entity is moving directly to the final coordinate instead of animating through the sequence. I suspect that there might be an issue with how the to()
function is used in conjunction with the loop.
Any guidance or suggestions on how to properly implement this step-by-step lerp animation would be greatly appreciated. Thank you!
here is my project link
https://playcanvas.com/editor/scene/1854319