Hi so this I am this basic newbie asking for help after looking by my self a fair amount of hours.
I am toy-programming a game where I use the smartphone orientation to trigger events. My problem is that I cannot get a variable value, which seems to be out of reach. The game is working pretty well if I send params for a function to one another but if I need to change the global variable so I can use it easily.
- It seems my variable is scoped and I do not understand how I can help it.
- In the sample below, how can I make the beta variable a global one?
- Is the variable scoped because of the if statement, the => or .then?
//The variable pression is the one I need to be global
let beta, gamma, pression=0, gameover=false, audio_source;
//displaying banner to authorize DeviceOrientationEvent on mobile
function bannerAuthorisation() {
if (window.DeviceOrientationEvent && typeof window.DeviceOrientationEvent.requestPermission === 'function'){
const banner = document.createElement('div');
banner.innerHTML = `<div id="autorisation" style="z-index: 1; position: absolute; width: 100%; background-color:#000; color: #fff" onclick="clickRequestDeviceOrientationEvent();"><p style="padding: 10px">Cliquez ici pour autoriser l'accès à votre capteur de mouvements.</p></div>`;
document.querySelector('body').appendChild(banner)
} else {
alert("Sorry you cannot play");
}
}
//If permission to play with DeviceOrientationEvent is granted, then I fetch beta and gamma
function clickRequestDeviceOrientationEvent() {
window.DeviceOrientationEvent.requestPermission()
.then(response => {
if (response === 'granted') {
window.addEventListener('deviceorientation', (e) => {
document.getElementById('autorisation').style.display = 'none';
//normalizing beta and gamma values and assigning it to global variables
beta=(Math.round(e.beta));
gamma=(Math.round(e.gamma));
//Here I send those values to another function and I can use it
increasePression();
}
)} else {
alert("Sorry you need to authorize the game to use it.")
}
})
.catch(e => {
console.error(e)
})
}
//Here I try to display the beta variable in HTML and it fails
//because I did not send params from above hte function above and it seems my var is not global
function test (){
document.getElementById("stuff").innerHTML = beta;
}