jsdoでdeviceorientation その4


概要

jsdoでdeviceorientationやってみた。

driving car作って見た。


写真


環境

nexus 7


サンプルコード

var lastOrientation;

function onDeviceOrientationChange(event) {
lastOrientation.gamma = event.gamma;
lastOrientation.beta = event.beta;
}
function deviceOrientationTest(event) {
window.removeEventListener('deviceorientation', deviceOrientationTest);
if (event.beta != null && event.gamma != null)
{
window.addEventListener('deviceorientation', onDeviceOrientationChange, false);
}
}
lastOrientation = {};
window.addEventListener('deviceorientation', deviceOrientationTest, false);
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var carWidth = [.25, .25];
var OFFSCREEN = document.createElement("canvas");
var OFFSCREEN_CTX = OFFSCREEN.getContext("2d");
var FOV = Math.PI / 3;
var DEPTH = 2 * Math.tan(FOV * 0.5);
var EYE = canvas.width / DEPTH;
var tex0 = new Image();
tex0.src = "/assets/a/h/Y/V/ahYVV.png";
OFFSCREEN.height = canvas.height;
OFFSCREEN.width = Math.ceil(canvas.height * DEPTH);
var player = {
x: 50,
y: 18,
z: 70,
a: Math.PI * 2,
vx: 0,
vy: 0,
vz: 0,
va: 0
};
function draw() {
var horizon = Math.floor(canvas.height * 0.01);
var scale = EYE * player.y;
var yMin = Math.ceil(scale / OFFSCREEN.height);
var yMax = canvas.height - horizon;
var near = scale / yMax - 1;
OFFSCREEN_CTX.clearRect(0, 0, OFFSCREEN.width, OFFSCREEN.height);
OFFSCREEN_CTX.save();
OFFSCREEN_CTX.translate(OFFSCREEN.width * 0.5, OFFSCREEN.height + near)
OFFSCREEN_CTX.rotate(Math.PI * 1.5 - player.a);
OFFSCREEN_CTX.drawImage(tex0, -player.x, -player.z);
OFFSCREEN_CTX.restore();
for (var y = yMin; y < yMax; y += height)
{
var top = scale / y,
width = top * DEPTH;
var height = Math.ceil(scale / Math.floor(top) - y);
var bottom = scale / (y + height);
ctx.drawImage(OFFSCREEN, (OFFSCREEN.width - width) * 0.5, OFFSCREEN.height + near - top, width, top - bottom, 0, horizon + y, canvas.width, height);
}
}
function update() {
var beta = lastOrientation.beta;
var gamma = lastOrientation.gamma;
if (beta > 20)
{
player.vx = 0;
player.vz = 0;
player.va = Math.sin(0.2);

}
else if (beta < -20)
{
player.vx = 0;
player.vz = 0;
player.va = Math.sin(-0.2);
}
else
{
player.vx = 0;
player.vz = 0;
player.va = 0;
}
if (gamma < -40)
{
player.vx = Math.cos(player.a) * 9;
player.vz = Math.sin(player.a) * 9;
}
player.x += player.vx;
player.z += player.vz;
player.a += player.va;
}
setInterval(function() {
update();
draw();
}, 500);


成果物

http://jsdo.it/ohisama1/qcdi

以上。