I have multiple menu’s in my scene. When I click on a button in my scene I want to update the position of the menu so that it stays in view. I thought this script would work but it does not update the position after the first time the menu was opened.
I think I’m missing something small!
OpenSelector.prototype.initialize = function() {
this.openSelectorButton.element.on('click', function() {
this.updatePositionMenu();
}, this);
};
OpenSelector.prototype.updatePositionMenu = function() {
const menuLayoutGroup = this.entity.children[11].children[0].children[0];
const offsetVehicleX = menuLayoutGroup.localPosition.x * -1;
const offsetVehicleY = menuLayoutGroup.localPosition.y * -1;
let defaultVehicleX = menuLayoutGroup.localPosition.x;
let defaultVehicleY = menuLayoutGroup.localPosition.y;
var worldPos = this.entity.localPosition;
var screenPos = new pc.Vec3();
// get screen space co-ord
this.camera.camera.worldToScreen(worldPos, screenPos);
// Take into account of pixel ratio
var pixelRatio = this.app.graphicsDevice.maxPixelRatio;
screenPos.x *= pixelRatio;
screenPos.y *= pixelRatio;
var device = this.app.graphicsDevice;
let anchorPosX = Math.floor(screenPos.x);
let anchorPosY = Math.floor(screenPos.y);
let deviceMiddleX = device.width / 2;
let deviceMiddleY = device.height / 2;
menuLayoutGroup.localPosition.x = defaultVehicleX;
menuLayoutGroup.localPosition.y = defaultVehicleY;
console.log('menuLocPosX before = ' + menuLayoutGroup.localPosition.x);
console.log('menuLocPosY before = ' + menuLayoutGroup.localPosition.y);
if (anchorPosX > deviceMiddleX) {
if (anchorPosY > deviceMiddleY) {
menuLayoutGroup.localPosition.x = offsetVehicleX;
console.log('Anchor is bottom right of the screen!');
} else {
menuLayoutGroup.localPosition.y = offsetVehicleY;
menuLayoutGroup.localPosition.x = offsetVehicleX;
console.log('Anchor is top right of the screen!');
}
} else {
if (anchorPosY > deviceMiddleY) {
console.log('Anchor is bottom left of the screen!');
} else {
menuLayoutGroup.localPosition.y = offsetVehicleY;
console.log('Anchor is top left of the screen!');
}
}
console.log('menuLocPosX after = ' + menuLayoutGroup.localPosition.x);
console.log('menuLocPosY after = ' + menuLayoutGroup.localPosition.y);
};