content/hifi-content/rebecca/WonderlandDrinks/shrinkEdible.js
2022-02-14 02:04:11 +01:00

74 lines
2.8 KiB
JavaScript

//
// shrinkEdible.js
//
// Created by Rebecca Stankus on 12/12/2018
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
(function() {
var SHRINK_SOUND = SoundCache.getSound(Script.resolvePath('assets/sounds/shrink.wav'));
var CHECK_RADIUS = 0.25; // distance from head at which item is considered "eaten"
var _this;
var injector;
function EdibleItem() {
_this = this;
}
EdibleItem.prototype = {
preload: function(entityID) {
_this.entityID = entityID;
},
// Here, we will check the distance between the item and the user's head. If it is close enough (determined by
// the CHECK_RADIUS value), we will delete the item, make the avatar shrink, and play the sound. We check
// for both head and neck joints to cover some cases where an avatar may not have a "Head" joint, for
// instance, Robimos.
checkIfNearHead: function() {
var position = Entities.getEntityProperties(_this.entityID, "position").position;
var foodDistance = CHECK_RADIUS * MyAvatar.scale;
if (Vec3.distance(position, MyAvatar.getJointPosition("Head")) < foodDistance ||
Vec3.distance(position, MyAvatar.getJointPosition("Neck")) < foodDistance) {
_this.playSound(SHRINK_SOUND, 0.1);
MyAvatar.scale *= 0.9;
Entities.deleteEntity(_this.entityID);
}
},
// When the user grabs the item, we begin checking the distance betweenthe item and the user's head for HMD
startNearGrab: function() {
Script.update.connect(_this.checkIfNearHead);
},
// We also want to check if the item is grabbed in desktop via mouseclick
startDistanceGrab: function() {
Script.update.connect(_this.checkIfNearHead);
},
// When the user releases the item, we will stop checking the distance. This will cover both desktop and HMD
releaseGrab: function() {
Script.update.disconnect(_this.checkIfNearHead);
},
// Checks for a sound already playing and if one is found, stops it. Then it plays the new sound
playSound: function(sound, volume) {
if (sound.downloaded) {
if (injector) {
injector.stop();
}
injector = Audio.playSound(sound, {
position: Entities.getEntityProperties(_this.entityID, 'position').position,
volume: volume,
localOnly: true
});
}
}
};
return new EdibleItem();
});