jsdoでdeviceorientation その3


概要

jsdoでdeviceorientationやってみた。

robot 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;
var ctx;
var G = 9.80665;
var a = 0;
var r = 0;
var V = 0;
var brake = 0;
var theta = rad(-90);
var col = "gray";
var car = {
'x': 0,
'y': 0,
'w': 50,
'h': 100,
'v_x': 0,
'v_y': 0,
'r': 0,
'n': 13000
};
var tire = {
'w': 10,
'h': 20,
'mu': 0.9
};
var tire_fr = {
'x': 15,
'y': -60,
'r': 0
};
var tire_fl = {
'x': -15,
'y': -60,
'r': 0
};
var tire_rr = {
'x': -20,
'y': -10,
'r': 0
};
var tire_rl = {
'x': 10,
'y': -10,
'r': 0
};
var engin = {
'a': 0.3,
'mu': 0.95
}
var world = {
'air_resist': 0.35
}
canvas = document.getElementById('mycanvas');
canvas.width = 800;
canvas.height = 400;
ctx = canvas.getContext('2d');
ctx.translate(canvas.width / 2, canvas.height / 2);
draw();
function rad(num) {
return num * Math.PI / 180;
}
function update() {
var L = Math.abs(tire_fr.y - tire_rr.y);
theta += (V / L) * Math.sin(rad(r));
car.x += V * Math.cos(rad(r)) * Math.cos(theta);
car.y += V * Math.cos(rad(r)) * Math.sin(theta);
car.r = theta;
var tred = Math.abs(tire_fr.x - tire_fl.x);
var R = L / Math.tan(rad(r));
tire_fl.r = Math.atan2(L , R + (tred / 2)) / Math.PI * 180;
tire_fr.r = Math.atan2(L , R - (tred / 2)) / Math.PI * 180;
}
function draw() {
ctx.save();
ctx.save();
ctx.fillStyle = 'rgba(256, 256, 256, 0.08)';
ctx.clearRect(-1 * canvas.width / 2, -1 * canvas.height / 2, canvas.width, canvas.height);
ctx.restore();
ctx.save();
ctx.translate(car.x, car.y);
ctx.rotate(rad(90));
ctx.rotate(car.r);
ctx.fillStyle = col;
ctx.fillRect(-car.w / 2, -80, car.w, car.h);
ctx.fillStyle = "blue";
ctx.save();
ctx.translate(tire_fr.x, tire_fr.y);
ctx.rotate(rad(tire_fr.r));
ctx.fillRect(-tire.w / 2, -tire.h / 2, tire.w, tire.h);
ctx.restore();
ctx.save();
ctx.translate(tire_fl.x, tire_fl.y);
ctx.rotate(rad(tire_fl.r));
ctx.fillRect(-tire.w / 2, -tire.h / 2, tire.w, tire.h);
ctx.restore();
ctx.fillRect(tire_rr.x, tire_rr.y, tire.w, tire.h);
ctx.fillRect(tire_rl.x, tire_rl.y, tire.w, tire.h);
ctx.fillRect(-1, -1, 2, 2);
ctx.restore();
ctx.restore();
}
setInterval(function() {
var beta = lastOrientation.beta;
var gamma = lastOrientation.gamma;
if (gamma < -40) V = 10;
else V = 0;
if (beta > 20) r = 20;
else if (beta < -20) r = -20;
else r = 0;
update();
draw();
}, 500);


成果物

http://jsdo.it/ohisama1/gnWL

以上。