Inertia compensated mouse position in Javascript - javascript

I am attempting to add an inertia type effect to my parallax background which is based on the current mouse position.
I have found a script that can take the position of the mouse, and make another object follow it with a set inertia within a fixed frame. However I would like to adapt this script so that I can create a function that I instead pass the current mouse x/y position and desired inertia, and it outputs the inertia compensated mouse position which I can then go on to pass to my parallax effect script. My code is below:
Parallax Script:
(function() {
// Add event listener
document.addEventListener("mousemove", parallax);
const elem = document.querySelector("#text");
// Magic happens here
function parallax(e) {
let _w = window.innerWidth/2;
let _h = window.innerHeight/2;
let _mouseX = e.clientX;
let _mouseY = e.clientY;
let _depth1 = `${50 - (_mouseX - _w) * 0.01}% ${50 - (_mouseY - _h) * 0.01}%`;
let _depth2 = `${50 - (_mouseX - _w) * 0.02}% ${50 - (_mouseY - _h) * 0.02}%`;
let _depth3 = `${50 - (_mouseX - _w) * 0.06}% ${50 - (_mouseY - _h) * 0.06}%`;
let x = `${_depth3}, ${_depth2}, ${_depth1}`;
console.log(x);
elem.style.backgroundPosition = x;
}
})();
Inertia Script:
class MouseTracking{
constructor(containerSelector, followerSelector, inertia = 10){
this.$container = document.querySelector(containerSelector);
this.$follower = document.querySelector(followerSelector);
this.inertia = inertia > 0 ? inertia : 1;
console.log(this.$container);
console.log(this.$follower);
this.getDims();
this.xPos = this.maxW/2;
this.yPos = this.maxH/2;
this.mouseX = this.maxW/2;
this.mouseY = this.maxH/2;
this.bindEvents();
this.update();
}
getDims(){
this.maxW = this.$container.clientWidth;
this.maxH = this.$container.clientHeight;
this.elemWidth = this.$follower.getBoundingClientRect().width;
this.elemHeight = this.$follower.getBoundingClientRect().height;
}
onMouse(e){
this.mouseX = e.clientX;
   this.mouseY = e.clientY;
}
bindEvents(){
window.onresize = ()=>{this.getDims()};
this.$container.addEventListener('mousemove', this.onMouse.bind(this));
}
update(){
let dX = this.mouseX - this.xPos - this.elemWidth/2;
let dY = this.mouseY - this.yPos - this.elemHeight/2;
this.xPos += (dX / this.inertia);
this.yPos += (dY / this.inertia);
this.xPrct = (100*this.xPos)/this.maxW;
this.yPrct = (100*this.yPos)/this.maxH;
this.$follower.style.transform = "translate3D("+this.xPos+"px, "+this.yPos+"px, 0)";
requestAnimationFrame(this.update.bind(this));
}
}
new MouseTracking('.background', '#cutout-text', 100);
Codepen for context here

Related

What is the maximum rate at which events are fired in a web browser?

I am trying to troubleshoot some of the performance issues I am encountering in a simple pixel painter app I am making. When the mouse is held down and a div is being hovered over, that div should change its background color. Which it does! The issue is that when moving the mouse rapidly certain divs are skipped along semi-regulars intervals. This suggests to me some sort of sampling problem.
I would be interested in knowing what the maximum frequency of event firings are for a web browser and whether this is specified in some standard (related to, say, ES6).
The situation for those who are interested:
More likely is that your painting code is still running when the next event comes in and that is dragging down your cpu. You need to cache just the mouse enter in the handler, and then do the painting work asynchronously to the events. Co-operative multitasking style.
As far as I know there is not any standard for the rate at wich the events can be fired. As what I experienced that depends on a lot of factors incuding the current users machine power.
Look, I made the drawing in this canvas of two lines of dots at a fixed Y position and at the current X position. The upper one was updated whith a while loop as frequent as the script could, the other one was drawn with the mouseMoved event. As you can see, the result is pretty much the same (even the dots in the MouseMove one are sometimes more often)
dots frecuency comparison
The time it takes for the event handler affects a lot, in fact I made the method to wait 1 second and then draw and the result was dots spaced for 5cm moving the mouse at the same speed.
So while the cpu is busy in an event handler it's more likely to not attend to new event triggers. My only recomendation is to stop the event propagation so it does not consume any resources and return false so the browser does not do any default behaviour.
Using a <canvas> can help you achieve a smoother behavior:
const scale = window.devicePixelRatio || 1;
const unit = 8;
const scaledUnit = unit * scale;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const offsetLeft = canvas.offsetLeft;
const offsetTop = canvas.offsetTop;
let drawing = false;
canvas.setAttribute('width', canvas.offsetWidth * scale);
canvas.setAttribute('height', canvas.offsetHeight * scale);
canvas.onmousedown = (e) => {
drawing = true;
paintPixel(Math.floor((e.pageX - offsetLeft) / unit), Math.floor((e.pageY - offsetTop) / unit));
};
canvas.onmouseup = (e) => {
drawing = false;
};
canvas.onmousemove = (e) => {
if (drawing) {
paintPixel(Math.floor((e.pageX - offsetLeft) / unit), Math.floor((e.pageY - offsetTop) / unit));
}
};
canvas.onmouseleave = (e) => {
paint = false;
};
function paintPixel(x, y) {
ctx.fillRect(x * scaledUnit, y * scaledUnit, scaledUnit, scaledUnit);
}
body {
margin: 0;
font-size: 0;
}
#canvas {
width: 100%;
height: 100vh;
}
<canvas id="canvas"></canvas>
However, to completely avoid those gaps, you would have to draw a line from one cursor position to the next instead of painting an individual "pixel".
I would use Bresenham's line algorithm to calculate all the points between consecutive events. Something like this:
const scale = window.devicePixelRatio || 1;
const unit = 8;
const scaledUnit = unit * scale;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const offsetLeft = canvas.offsetLeft;
const offsetTop = canvas.offsetTop;
let drawing = false;
let lastX = null;
let lastY = null;
canvas.setAttribute('width', canvas.offsetWidth * scale);
canvas.setAttribute('height', canvas.offsetHeight * scale);
canvas.onmousedown = (e) => {
drawing = true;
lastX = Math.floor((e.pageX - offsetLeft) / unit);
lastY = Math.floor((e.pageY - offsetTop) / unit);
paintPixel(lastX, lastY);
};
canvas.onmouseup = (e) => {
drawing = false;
};
canvas.onmousemove = (e) => {
if (drawing) {
const x = Math.floor((e.pageX - offsetLeft) / unit);
const y = Math.floor((e.pageY - offsetTop) / unit);
const w = Math.abs(x - lastX);
const h = Math.abs(y - lastY);
if (w === 0 && h === 0) {
paintPixel(x, y);
} else if (w > h) {
lineLandscape(lastX, lastY, x, y);
} else {
linePortrait(lastX, lastY, x, y);
}
lastX = x;
lastY = y;
}
};
canvas.onmouseleave = (e) => {
paint = false;
};
function paintPixel(x, y) {
ctx.fillRect(x * scaledUnit, y * scaledUnit, scaledUnit, scaledUnit);
}
function lineLandscape(x0, y0, x1, y1) {
if (x0 > x1) {
[x0, x1] = [x1, x0];
[y0, y1] = [y1, y0];
}
const dx = x1 - x0;
const dy = Math.abs(y1 - y0);
const yi = y0 > y1 ? -1 : 1;
let D = 2 * dy - dx;
let y = y0;
for (let x = x0; x <= x1; ++x) {
paintPixel(x, y);
if (D > 0) {
y += yi;
D -= 2 * dx;
}
D += 2 * dy;
}
}
function linePortrait(x0, y0, x1, y1) {
if (y0 > y1) {
[x0, x1] = [x1, x0];
[y0, y1] = [y1, y0];
}
const dx = Math.abs(x1 - x0);
const dy = y1 - y0;
const xi = x0 > x1 ? -1 : 1;
let D = 2 * dx - dy;
let x = x0;
for (let y = y0; y <= y1; ++y) {
paintPixel(x, y);
if (D > 0) {
x += xi;
D -= 2 * dy;
}
D += 2 * dx;
}
}
body {
margin: 0;
font-size: 0;
}
#canvas {
width: 100%;
height: 100vh;
}
<canvas id="canvas"></canvas>
You can also adapt that algorithm to work with your approach if you really need to use <div>s.

Moving a sprite to click location and stop there PIXIJS

This simple game makes a sprite move around to the position a user clicks. I got it working that the sprite moves to the location, but I need to make it stop at the click location. This code makes the sprite only stop at the click location when the sprite moves towards the bottom right corner. How do I fix this to make it always stop at the click location?
var Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite;
var stage = new PIXI.Container(),
renderer = PIXI.autoDetectRenderer(1000, 1000);
document.body.appendChild(renderer.view);
PIXI.loader
.add("animal.png")
.load(setup);
var rocket, state;
function setup() {
//Create the `tileset` sprite from the texture
var texture = PIXI.utils.TextureCache["animal.png"];
//Create a rectangle object that defines the position and
//size of the sub-image you want to extract from the texture
var rectangle = new PIXI.Rectangle(192, 128, 32, 32);
//Tell the texture to use that rectangular section
texture.frame = rectangle;
//Create the sprite from the texture
rocket = new Sprite(texture);
rocket.anchor.x = 0.5;
rocket.anchor.y = 0.5;
rocket.x = 50;
rocket.y = 50;
rocket.vx = 0;
rocket.vy = 0;
//Add the rocket to the stage
stage.addChild(rocket);
document.addEventListener("click", function(){
rocket.clickx = event.clientX;
rocket.clicky = event.clientY;
var x = event.clientX - rocket.x;
var y = event.clientY - rocket.y;
rocket.vmax = 5;
var total = Math.sqrt(x * x + y * y);
var tx = x/total;
var ty = y/total;
rocket.vx = tx*rocket.vmax;
rocket.vy = ty*rocket.vmax;
});
state = play;
gameLoop();
}
function gameLoop() {
//Loop this function at 60 frames per second
requestAnimationFrame(gameLoop);
state();
//Render the stage to see the animation
renderer.render(stage);
}
function play(){
rocket.x += rocket.vx;
rocket.y += rocket.vy;
if(rocket.x >= rocket.clickx){
if(rocket.y >= rocket.clicky){
rocket.x = rocket.clickx;
rocket.y = rocket.clicky;
}
}
}
So your sprite has the velocity 5. Then let's just check out the distance between the sprite and the stop position. Whenever it's less than 5, make it stop at the position.
function play(){
var dx = rocket.x - rocket.clickx;
var dy = rocket.y - rocket.clicky;
if (Math.sqrt(dx * dx + dy * dy) <= 5) {
rocket.x = rocket.clickx;
rocket.y = rocket.clicky;
}
else {
rocket.x += rocket.vx;
rocket.y += rocket.vy;
}
}
You can modify the if statement like below to avoid Math.srqt call.
if ((dx * dx + dy * dy) <= (5 * 5)) {

Create a div like element that has overflow set to auto using HTML Canvas

The title might be misleading but that is the best I could come up with for a summary of my question.
Anyways, I need to figure out how to make a list, or a container, in this case a plain rectangle that contains a list of items, which can be dragged up and down in order to reveal other items in the container. In a way it would resemble a constrained div with a slider bar, but without the slider.
Now, I have an idea on using KonvaJS, former KineticJS to put all the items in the container in a group, and make the group draggable in certain directions, etc.
However the catch is that the sliding of the elements top or down should not only be on drag, but on flick also. So if you kind of flick your finger/mouse upwards the list would keep sliding by, until the end, where the speed would vary based on the flick intensity. If determining the flick intensity or speed is too complicated, then just any type of flick would need to slide the whole list to the bottom, or top.
So this should kind of resemble the standard vertical slide widgets you have on your android or ios. Now do you have any ideas on how I can proceed with this, or how would you go about this. Any ideas are welcome.
Working demo: http://jsbin.com/gefuvu/edit?js,output
Usual drag and drop is already supported by draggable property. For limit drag&drop to vertical scrolling I am using this simple dragBound:
const group = new Konva.Group({
draggable: true,
dragBoundFunc: (pos) => {
const minY = -group.getClientRect().height + stage.height();
const maxY = 0;
const y = Math.max(Math.min(pos.y, maxY), minY);
return {y, x: 0}
}
});
"Flick" implementation:
// setup flick
let lastY = null;
let dY = 0;
group.on('dragstart', () => {
lastY = group.y();
dy = 0;
});
group.on('dragmove', () => {
dy = lastY - group.y();
lastY = group.y();
});
group.on('dragend', () => {
// if last move is far way it means user move pointer very fast
// for this case we need to automatically "scroll" group
if (dy > 5) {
group.to({
y: -group.getClientRect().height + stage.height()
});
}
if (dy < -5) {
group.to({
y: 0
});
}
});
I guess that when you talk about "flick" you actually mean "scroll".
Edit : Missed the point of the question, also missed the [konvajs] tag. But here is a way to do it without any library, hoping it may help someone coming this way.
The simplest idea is to make two objects, a container and a content, each one with a canvas.
On mouse's wheel event, update the content position, then redraw its canvas to the container's one or if you need to handle drag, listen to the mousemove event, set a dragging flag to true, that you remove on mouseup. On mousemove update the position after you calculated the moving speed by checking the last event's timestamp and the new one's. Then on mouseup, start an animation that will decrease the speed of your movement :
// our container object
var container = {
width: window.innerWidth - 2,
height: window.innerHeight - 2,
top: 0,
left: 0,
canvas: document.getElementById('container'),
isOver: function(x, y) {
return (x >= this.left && x <= this.left + this.width &&
y >= this.top && y <= this.top + this.height);
},
};
// our content object
var content = {
width: container.width * 2,
height: container.height * 2,
top: 0,
left: 0,
background: 'rgba(0,255,0,.5)',
canvas: document.createElement('canvas'),
// set an init function to draw the texts
init: function() {
var ctx = this.ctx;
ctx.font = '20px sans-serif';
ctx.textBaseline = 'top';
ctx.fillText('Hello World', 0, 0);
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillText('Middle world', this.width / 2, this.height / 2);
ctx.textBaseline = 'bottom';
ctx.textAlign = 'left';
var textLength = ctx.measureText('Bye World').width;
ctx.fillText('Bye World', this.canvas.width - textLength, this.canvas.height);
ctx.fillStyle = this.background;
ctx.fillRect(0, 0, this.width, this.height);
},
};
// init the objects
var init = function(obj) {
var c = obj.canvas;
obj.ctx = c.getContext('2d');
c.width = obj.width;
c.height = obj.height;
if (obj.init) {
obj.init();
}
}
// our drawing function
var draw = function() {
container.ctx.clearRect(0, 0, container.width, container.height);
container.ctx.drawImage(content.canvas, content.left, content.top);
};
// update the content position
container.update = function(x, y) {
// if the content is smaller, we don't need to scroll
if (content.width > container.width) {
var maxX = Math.max(container.width, content.width);
var minX = Math.min(container.width, content.width);
content.left -= x;
// if we are at one end
if (content.left < minX - maxX) {
content.left = minX - maxX;
} // or another
else if (content.left > 0) {
content.left = 0;
}
}
if (content.height > container.height) {
var maxY = Math.max(container.height, content.height);
var minY = Math.min(container.height, content.height);
content.top -= y;
if (content.top < minY - maxY) {
content.top = minY - maxY;
} else if (content.top > 0) {
content.top = 0;
}
}
};
var drag = {
friction: .1,
sensibility: 18,
minSpeed: .01,
};
var mouseMove_Handler = function(e) {
// we're not dragging anything, stop here
if (!drag.dragged) {
return;
}
var rect = this.getBoundingClientRect();
var posX = e.clientX - rect.left;
var posY = e.clientY - rect.top;
// how long did it take since last event
var deltaTime = (e.timeStamp - drag.lastDragTime) / drag.sensibility;
// our moving speed
var deltaX = (drag.lastDragX - posX) / deltaTime;
var deltaY = (drag.lastDragY - posY) / deltaTime;
// update the drag object
drag.lastDragX = posX;
drag.lastDragY = posY;
drag.lastDeltaX = deltaX;
drag.lastDeltaY = deltaY;
drag.lastDragTime = e.timeStamp;
// update the container obj
drag.dragged.update(deltaX, deltaY);
// redraw
draw();
};
var mouseDown_Handler = function(e) {
// if we are sliding, stop it
if (drag.sliding) {
cancelAnimationFrame(drag.sliding);
drag.sliding = null;
}
var rect = this.getBoundingClientRect();
var posX = e.clientX - rect.left;
var posY = e.clientY - rect.top;
// first check that the event occurred on top of our container object
// we could loop through multiple ones
if (container.isOver(posX, posY)) {
// init our drag object
drag.dragged = container;
drag.lastDragX = posX;
drag.lastDragY = posY;
drag.lastDragTime = e.timeStamp;
}
};
var mouseUp_Handler = function(e) {
// store a ref of which object we were moving
var container = drag.dragged;
// we're not dragging anymore
drag.dragged = false;
var slide = function() {
// decrease the speed
drag.lastDeltaX /= 1 + drag.friction;
drag.lastDeltaY /= 1 + drag.friction;
// check that we are still out of our minimum speed
if (drag.lastDeltaX > drag.minSpeed || drag.lastDeltaY > drag.minSpeed ||
drag.lastDeltaX < -drag.minSpeed || drag.lastDeltaY < -drag.minSpeed) {
// store a reference of the animation
drag.sliding = requestAnimationFrame(slide);
} else {
drag.sliding = null;
drag.lastDeltaX = drag.lastDeltaY = 0;
}
container.update(drag.lastDeltaX, drag.lastDeltaY);
draw();
};
slide();
};
// add the wheel listener, for a polyfill check the MDN page :
// https://developer.mozilla.org/en-US/docs/Web/Events/wheel#Listening_to_this_event_across_browser
var mouseWheel_Handler = function(e) {
// get the position of our canvas element
var rect = this.getBoundingClientRect();
var posX = e.clientX - rect.left;
var posY = e.clientY - rect.top;
// first check that the event occurred on top of our container object
if (container.isOver(posX, posY)) {
// tell the browser we handle it
e.preventDefault();
e.stopPropagation();
// send the event's deltas
container.update(e.deltaX, e.deltaY);
// redraw
draw();
}
};
container.canvas.addEventListener('mousedown', mouseDown_Handler);
container.canvas.addEventListener('mousemove', mouseMove_Handler);
container.canvas.addEventListener('mouseup', mouseUp_Handler);
container.canvas.addEventListener('mouseleave', mouseUp_Handler);
container.canvas.addEventListener('wheel', mouseWheel_Handler);
// init the objects
init(container);
init(content);
// make a first draw
draw();
// Snippet only preventions \\
// avoid the outer window to scroll
window.onscroll = function(e) {
e.preventDefault();
e.stopPropagation()
};
// if you go in full page view
window.onresize = function() {
container.width = window.innerWidth;
container.height = window.innerHeight;
content.width = container.width * 2;
content.height = container.height * 2;
init(container);
init(content);
draw();
};
body,html,canvas {
margin: 0;
display: block
}
canvas {
border: 1px solid;
}
<canvas id="container"></canvas>

Javascript animation easing

I have a function which moves my canvas using an ease in aspect. The problem how ever is the canvas animation doesn't work. It just scrolls too far and what appears to be too fast as well.
This is my function which moves the camera to the location the user clicked on the canvas:
function moveCamera(e,parent){
clearInterval(parent.scroll);
var mouseData = mousePos(evt,parent); //get x:y relative to element
var initial = {'x':el.width/2,'y':el.height/2},
target = {'x':mouseData.x,'y':mouseData.y},
deltaX = target.x-initial.x,
deltaY = target.y-initial.y,
timeStart = Date.now(),
timeLength = 800,
x,y,deltaTime;
function update(){
function fraction(t){
x = (target.x - initial.x) - (t*deltaX),
y = (target.y - initial.y) - (t*deltaY);
camera.x -= x;
camera.y -= y;
}
function easing(x) {
return 0.5 + 0.5 * Math.sin((x - 0.5) * Math.PI);
}
deltaTime = (Date.now() - timeStart) / timeLength;
if (deltaTime > 1) {
fraction(1);
} else {
fraction(easing(deltaTime));
}
}
parent.scroll = setInterval(update, 10);
}
I have attatched a JSFiddle of the issue demonstrated: http://jsfiddle.net/p5xjmLay/ simply click on the canvas to scroll to that position, and you will see it goes a bit crazy.
I am wondering how to solve this so the camera offset changes correctly each time?
I changed a little bit your version and it seems that it is working, please try this:
var el = document.getElementById('canvas'),
initial = {'x':el.width/2,'y':el.height/2},
ctx = el.getContext('2d'),
camera = {'x':el.width/2,'y':el.height/2},
box = {'x':0,'y':0};
var x,y,deltaTime;
el.addEventListener('mousedown',function(e){moveCamera(e,this);},false);
function moveCamera(e,parent){
clearInterval(parent.scroll);
var mouseData = mousePos(e,parent);
target = {'x':mouseData.x,'y':mouseData.y},
deltaX = target.x-initial.x,
deltaY = target.y-initial.y,
timeStart = Date.now(),
timeLength = 800;
function update(){
function fraction(t){
x = target.x - (initial.x + (t*deltaX)),
y = target.y - (initial.y + (t*deltaY));
if (Math.abs(camera.x + x - target.x) > Math.abs(camera.x - target.x)) {
camera.x = target.x;
initial.x = target.x;
} else {
camera.x += x;
}
if (Math.abs(camera.y + y - target.y) > Math.abs(camera.y - target.y)) {
camera.y = target.y;
initial.y = target.y;
} else {
camera.y += y;
}
}
function easing(x) {
return 0.5 + 0.5 * Math.sin((x - 0.5) * Math.PI);
}
deltaTime = (Date.now() - timeStart) / timeLength;
if (deltaTime > 1) {
fraction(1);
} else {
fraction(easing(deltaTime));
}
draw();
}
parent.scroll = setInterval(update, 200);
}
function mousePos(evt,el){
var offsetX = 0,
offsetY = 0;
do{
offsetX += el.offsetLeft - el.scrollLeft;
offsetY += el.offsetTop - el.scrollTop;
}while(el = el.offsetParent){
return {'x':evt.pageX - offsetX, 'y':evt.pageY - offsetY}
}
}
function draw(){
ctx.clearRect(0,0,el.width,el.height);
ctx.save();
ctx.translate(camera.x,camera.y);
ctx.beginPath();
ctx.rect(box.x-25, box.y-25,50,50);
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
}
draw();

Conflicting JavaScript for gyroscope move and touchmove on iOS, how do I pause one part when the second is in use?

I'm punching above my weight a bit with some JavaScript code on an iOS web app.
What I'm doing is moving a layer above another layer using:
Gyro and accelerometer data and
Touch input.
This means I've got two bits of javascript both trying to move the same thing. This doesn't work so well, as you can see from the current version when viewed on an iOS device (hint: the transparency is turned on with the button on the right, and no, it can't be moved with a mouse right now and wont move unless you are using an iOS device with a Gyro).
So I've done the hard bits but I'm stuck on what I expect is a gotcha based on my newb(ish) level of proficiency with JavaScript.
How can I stop the gyro-move code when the touch-move code is active? Also I guess I'll need to update the x+y values so the transparency does not jump position once the touch-move ends.
I've tried adding an if, else statement to the top of the code but this seems to break the whole lot.
BTW thanks to everyone on StackOverflow, previous Q and As have been tons of help in getting me this far.
Help will be most appreciated.
Stefan
Here's my code so far, it's living in the body element...
var x = 0, y = 0,
vx = 0, vy = 0,
ax = 0, ay = 0;
var transp = document.getElementById("transp");
if (window.DeviceMotionEvent != undefined) {
window.ondevicemotion = function(e) {
ax = event.accelerationIncludingGravity.x * 5;
ay = event.accelerationIncludingGravity.y * 5 + 19;
document.getElementById("accelerationX").innerHTML = e.accelerationIncludingGravity.x;
document.getElementById("accelerationY").innerHTML = e.accelerationIncludingGravity.y;
document.getElementById("accelerationZ").innerHTML = e.accelerationIncludingGravity.z;
if ( e.rotationRate ) {
document.getElementById("rotationAlpha").innerHTML = e.rotationRate.alpha;
document.getElementById("rotationBeta").innerHTML = e.rotationRate.beta;
document.getElementById("rotationGamma").innerHTML = e.rotationRate.gamma;
}
}
setInterval( function() {
var landscapeOrientation = window.innerWidth/window.innerHeight > 1;
if ( landscapeOrientation) {
vx = vx + ay;
vy = vy + ax;
} else {
vy = vy - ay;
vx = vx + ax;
}
vx = vx * 0.98;
vy = vy * 0.98;
y = parseInt(y + vy / 70);
x = parseInt(x + vx / 70);
boundingBoxCheck();
transp.style.top = y + "px";
transp.style.left = x + "px";
}, 25);
}
function boundingBoxCheck(){
if (x<-310) { x = -310; vx = -vx; }
if (y<-300) { y = -300; vy = -vy; }
if (x>document.documentElement.clientWidth) { x = document.documentElement.clientWidth; vx = -vx; }
if (y>document.documentElement.clientHeight+400) { y = document.documentElement.clientHeight+400; vy = -vy; }
}
$.fn.moveable = function() {
var offset = null;
var start = function(e) {
var orig = e.originalEvent;
var pos = $(this).position();
offset = {
x: orig.changedTouches[0].pageX - pos.left,
y: orig.changedTouches[0].pageY - pos.top
};
};
var moveMe = function(e) {
e.preventDefault();
var orig = e.originalEvent;
$(this).css({
top: orig.changedTouches[0].pageY - offset.y,
left: orig.changedTouches[0].pageX - offset.x
});
};
this.bind("touchstart", start);
this.bind("touchmove", moveMe);
};
$(".moveable").moveable();
My first thought would be is to have an isTouching variable that gets set to true on touchstart and set back to false on touchEnd. Then using a conditional the gyro code will only run if the isTouching variable is false. Hope that helps.

Categories

Resources