# Complete a simple game with mobile gyroscope

Control the movement of the ball by rotating the mobile phone

The event.beta property, which represents the rotation along the X axis, has a value range of [- 180, 180).

Control the left and right movement of the ball The event.gamma property indicates the rotation along the Y axis, and its value range is [- 90, 90). Indicates up and down movement  When the horizontal and vertical screens are switched, the coordinate axis needs to be changed

In order to avoid too long movement, it is also necessary to set a rate ratio to take the mold for the angle, so as to avoid the problem of large angle caused by too much deflection

When binding functions, try to use arrow function to avoid this pointing error... Debugging this is really annoying... I can't see console on the mobile phone....

``````<template>
<div class="container">
<!--<div>-->
<!--<div>{{nalpha}}</div>-->
<!--<div>{{nbeta}}</div>-->
<!--<div>{{ngamma}}</div>-->
<!--</div>-->

<div class="ball" ref="ball" id="ball"></div>
</div>
</template>

<script>
export default {
name: "simple-game",
data() {
return {
alpha: 0,
beta: 0,
gamma: 0,
isInit: false,
nalpha: 0,
nbeta: 0,
ngamma: 0,
left: 0,
top: 0,
}
},
methods: {
refresh() {
// Ratio converted from angle to movement rate
let rate = 5
this.left += parseInt(this.ngamma / rate)
// console.log(this.\$refs.ball.style)
// document.getElementById('ball').style.left = '' + this.left + 'px'
this.top += parseInt(this.nbeta / rate)
// document.getElementById('ball').style.top = '' + this.top + 'px'
this.\$refs.ball.style.left = this.left + 'px'
this.\$refs.ball.style.top = this.top + 'px'

// console.log(this.\$refs.ball.style.left);
},
},
mounted() {
//Judge the horizontal and vertical screen status of the mobile phone:

// To facilitate the operation, move the ball to the center every time the screen is switched
let hengshuping = () => {
this.left = 0
this.top = 0
if (window.orientation == 180 || window.orientation == 0) {

if (!this.isInit) {
this.alpha = event.alpha
this.beta = event.beta
this.gamma = event.gamma
this.isInit = true
}
this.nalpha = event.alpha - this.alpha
this.nbeta = event.beta - this.beta
this.ngamma = event.gamma - this.gamma
this.refresh()
});
}

if (window.orientation == 90 || window.orientation == -90) {
if (!this.isInit) {
this.alpha = event.alpha
this.beta = event.beta
this.gamma = event.gamma
this.isInit = true
}
this.nalpha = (event.gamma - this.gamma) % 180
this.nbeta = -(event.gamma - this.gamma) % 90
this.ngamma = event.beta - this.beta
this.refresh()
}, false);
}
}
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
hengshuping()
}

}
</script>

<style scoped>
.container {
width: 100vw;
height: 100vh;
display: flex;
/*position: relative;*/
justify-content: center;
align-items: center;
}

.ball {
width: 50px;
height: 50px;
background: deepskyblue;