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

76 lines
3 KiB
JavaScript

//
// edibleItem.js
//
// created by Rebecca Stankus on 11/13/18
// Copyright 2018 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
// This client script will be on the candy cane and gingerbread man so that when a user the item and places it
// near their head, the item will disappear and a crunch sound will be heard.
(function() {
var GROW_SOUND = SoundCache.getSound(Script.resolvePath('assets/sounds/grow.mp3'));
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 grow, and play the "eating" 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(GROW_SOUND, 0.1);
MyAvatar.scale = 0.9;
Entities.deleteEntity(_this.entityID);
}
},
// When the user grabs the item, we begin checking the distance between the 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();
});