xxxxxxxxxx
76
<html>
<head>
<title>HTML5 Game with Sensor Control</title>
<style>
#gameCanvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// Get the canvas element
const canvas = document.getElementById("gameCanvas");
const context = canvas.getContext("2d");
// Set initial position and velocity
let x = canvas.width / 2;
let y = canvas.height / 2;
let dx = 0;
let dy = 0;
// Start listening to device motion
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', handleMotion);
}
// Handle device motion event
function handleMotion(event) {
// Get accelerometer data
const { x: ax, y: ay } = event.accelerationIncludingGravity;
// Adjust ball velocity based on accelerometer data
dx = ax * 0.1;
dy = ay * 0.1;
}
// Draw the ball
function drawBall() {
context.beginPath();
context.arc(x, y, 10, 0, Math.PI * 2);
context.fillStyle = "#0095DD";
context.fill();
context.closePath();
}
// Update game logic and redraw
function draw() {
// Clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw ball
drawBall();
// Update ball position
x += dx;
y += dy;
// Bounce off walls
if (x + dx > canvas.width - 10 || x + dx < 10) {
dx = -dx;
}
if (y + dy > canvas.height - 10 || y + dy < 10) {
dy = -dy;
}
requestAnimationFrame(draw);
}
// Start the game
draw();
</script>
</body>
</html>