How to detect last device motion event using javascript? - javascript

Good day all,
I am trying to capture the values of accelerationIncludingGravity in javascript just before it stops generating any more, that is, when the device is stationary. I know that there is an event called motionEnded generated in Xcode to capture this, but I would like to perform the same thing using javascript to make it device independent.
Thanks in advance for the effort.
Here is the full HTML code ... Most of it is for measuring the last DeviceMotion event...
<script type="text/javascript">
var x = 0, y = 0, vx = 0, vy = 0, ax = 0, ay = 0, accX = 0, accY = 0, accZ = 0, readingStarted = 0, readingCompleted = 0, buttonPress = 0, test = 0, toleranceCounter = 0;
function throttle (callback, limit) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait) { // If we're not waiting
callback.call(); // Execute users function
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
wait = false; // And allow future invocations
}, limit);
}
}
}
function myFunction() {
if(buttonPress == 0)
{
readingStarted = 0;
readingCompleted = 0;
toleranceCounter = 0;
test = 0;
window.addEventListener('devicemotion', throttle (handleMotionEvent, 200), false);
}
if ((buttonPress < 6) && ((readingStarted == 0) || (readingCompleted ==1)))
{
readingStarted = 0;
readingCompleted = 0;
toleranceCounter = 0;
buttonPress = buttonPress + 1;
}
document.getElementById("buttonp").innerHTML = buttonPress;
document.getElementById("test").innerHTML = test;
}
function handleMotionEvent(e)
{
test = test + 1;
if (readingCompleted == 1)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
passToPHP2(accX, accY, accZ);
}
else if ( (readingStarted == 0) && (readingCompleted == 0) &&
(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = e.accelerationIncludingGravity.x;
accY = e.accelerationIncludingGravity.y;
accZ = e.accelerationIncludingGravity.z;
readingStarted = 1;
if ( e.rotationRate ) {
document.getElementById("rotationAlpha").innerHTML = e.rotationRate.alpha;
document.getElementById("rotationBeta").innerHTML = e.rotationRate.beta;
document.getElementById("rotationGamma").innerHTML = e.rotationRate.gamma;
}
}
else if ( (readingStarted == 1) && (readingCompleted == 0) && (toleranceCounter < 5) &&
!(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
toleranceCounter = toleranceCounter + 1;
}
else if ( (readingStarted == 1) && (readingCompleted == 0) && (toleranceCounter == 5) &&
!(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
passToPHP(accX, accY, accZ);
readingCompleted = 1;
}
else if ( (readingStarted == 1) && (readingCompleted == 0) &&
(((accX - e.accelerationIncludingGravity.x) > 0.1) || ((accX - e.accelerationIncludingGravity.x) < -0.1) ||
((e.accelerationIncludingGravity.x - accX) > 0.1) || ((e.accelerationIncludingGravity.x - accX) < -0.1) ||
((accY - e.accelerationIncludingGravity.y) > 0.1) || ((accY - e.accelerationIncludingGravity.y) < -0.1) ||
((e.accelerationIncludingGravity.y - accY) > 0.1) || ((e.accelerationIncludingGravity.y - accY) < -0.1) ||
((accZ - e.accelerationIncludingGravity.z) > 0.1) || ((accZ - e.accelerationIncludingGravity.z) < -0.1) ||
((e.accelerationIncludingGravity.z - accZ) > 0.1) || ((e.accelerationIncludingGravity.z - accZ) < -0.1))
)
{
accX = (accX + e.accelerationIncludingGravity.x) / 2;
accY = (accY + e.accelerationIncludingGravity.y) / 2;
accZ = (accZ + e.accelerationIncludingGravity.z) / 2;
toleranceCounter = 0;
}
document.getElementById("accelerationX").innerHTML = accX;
document.getElementById("accelerationY").innerHTML = accY;
document.getElementById("accelerationZ").innerHTML = accZ;
}
function passToPHP(x, y, z)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost/acc.php?accX=" + x + "&accY=" + y + "&accZ=" + z, true);
xhttp.send();
}
function passToPHP2(x, y, z)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost/acc2.php?accX=" + x + "&accY=" + y + "&accZ=" + z, true);
xhttp.send();
}
</script>

Related

X Position of a Variable Becoming Negative

I'm having a problem in my code where the initial x and y values (gx and gy) start out as positive, then jump to negative at around the third loop (specifically to coordinates (-8, 12)), then continue on as normal. I've checked multiple times, and there is only one thing that changes the variables. However, it doesn't set them to a negative number. Why does it keep going to that particular point?
Edit: To clarify, the fact that gx and gy become negative isn't the issue so much as the fact that they jump to (-8, 12) after being at (355, 350) for two loops. I'm unclear on why this happens, and have not been able to troubleshoot it yet. Any ideas why it goes to that point?
Also, it may be worth noting that I'm using a web editor called p5.js.
Here is my code:
var ris = 0;
var hyp = 0;
var gx = 355;
var gy = 350;
var count = 1;
var rem = 0
var dir = 0
var xdir = 1
var ydir = 1
var cx = 0
var cy = 0
var xpos = 200;
var ypos = 200;
var moveHoriz = 0;
var moveVert = 0;
function gmove(){
if (gx == xpos){
cx = 1
} else if(gy == ypos){
cy = 1
}
if (cx == 1 && cy == 1){
console.log("this functions");
if ((400 - gx)-(400-xpos) < 0 && (400-gy)-(400-ypos) == 0){
xdir = -1
ydir = 1
} else if ((400 - gx)-(400-xpos) < 0 && (400-gy)-(400-ypos) > 0){
xdir = -1
ydir = -1
} else if ((400 - gx)-(400-xpos) == 0 && (400-gy)-(400-ypos) > 0){
xdir = 1
ydir = -1
} else if ((400 - gx)-(400-xpos) > 0 && (400-gy)-(400-ypos) > 0){
xdir = -1
ydir = -1
} else if ((400 - gx)-(400-xpos) > 0 && (400-gy)-(400-ypos) > 0){
xdir = -1
ydir = 1
print("yeeeee")
} else if ((400 - gx)-(400-xpos) > 0 && (400-gy)-(400-ypos) < 0){
xdir = -1
ydir = -1
print("yeeeeee")
} else if ((400 - gx)-(400-xpos) == 0 && (400-gy)-(400-ypos) < 0){
xdir = 1
ydir = -1
print("yeeeeeee")
} else if ((400 - gx)-(400-xpos) < 0 && (400-gy)-(400-ypos) < 0){
xdir = -1
ydir = -1
print("yeeeeeeee")
}
} else {
ellipse(gx, gy, 20, 20);
ris = (ypos-gy);
run = (xpos-gx);
hyp = pow(ris, 2) + pow(run, 2);
hyp = sqrt(hyp);
stroke(0);
line(gx, gy, xpos, ypos);
console.log(xpos+10, ypos+10, gx-10, gy+10);
hyp = hyp/(100*hyp);
if ((400 - gx)-(400-xpos) > -30 && (400-gx)-(400-xpos) < 30 && (400-ypos)-(400-gy) > -30 && (400-ypos)-(400-gy) < 30){
if(count == 1){
rem = round(gx/400);
count = count + 1;
}
} else {
if(count == 1){
rem = round(gx/400);
count = count + 1;
} else {
gx = xdir*(rem*count);
console.log("math:", ydir*(rem*count))
gy = ydir*(rem*count);
count = count + 1;
ellipse(gx, gy, 20, 20);
console.log(count);
}
}
cx = 0;
cy = 0;
}
}
function setup() {
//this part isn't relevant either
createCanvas(400, 400);
print(gx, gy);
}
//this is a forever loop
function draw() {
background(255);
gmove();
ellipse(xpos, ypos, 20, 20);
}
}
//everything below this point is also irrelevant; it just makes an ellipse move with wasd
function keyPressed(){
if (key == "a") {
moveHoriz = -1;
ellipse(xpos, ypos, 20, 20);
}
if (key == "d") {
moveHoriz = 1;
ellipse(xpos, ypos, 20, 20);
}
if (key == "w"){
moveVert = -1;
ellipse(xpos, ypos, 20, 20);
}
if (key == "s"){
moveVert = 1;
ellipse(xpos, ypos, 20, 20);
}
}
function keyReleased(){
if (key == "d") {
moveHoriz = 0;
}
if (key == "a") {
moveHoriz = 0;
}
if (key == "s"){
moveVert = 0;
}
if (key == "w"){
moveVert = 0;
}
}
Apologies for the length, and thank you for taking the time to look at this!

Simplifying IF/ELSE condition

I want to ask how can I simplify my code? It seems hard to read and has too much if-else condition here. Any way to simplify the code?
if (e.shiftKey && this.idx > 0) {
this.idx= this.idx - 1;
} else if (!e.shiftKey && this.idx < trapFocus.length - 1) {
this.idx = this.idx + 1;
} else if (!e.shiftKey && this.idx < trapFocus.length + 1) {
this.idx= this.idx - 2;
} else if (e.shiftKey && this.idx > - 1) {
this.idx= this.idx + 2;
}
You can simply separate the condition using separate if-else
if (e.shiftKey){
if(this.idx > 0) this.idx = this.idx - 1;
else if(this.idx > -1) this.idx = this.idx + 2;
} else {
if(this.idx < trapFocus.length - 1)) this.idx = this.idx + 1;
else if(this.idx < trapFocus.length + 1) this.idx < trapFocus.length + 1
}
This first thing you could do is to factor out e.shiftKey and use += and -= operators
if(e.shiftKey)
{
if(this.idx > 0)
{
this.idx -= 1;
}
else if(this.idx > -1)
{
this.idx += 2;
}
}
else{
if(this.idx < trapFocus.length - 1)
{
this.idx += 1;
}
else if(this.idx < trapFocus.length + 1)
{
this.idx -= 2;
}
}
If you ever want to go with ternaries:
this.idx += e.shiftKey ? (
this.idx > 0 ? -1 :
this.idx > -1 ? 2 : 0
) : (
this.idx < trapFocus.length - 1 ? 1 :
this.idx < trapFocus.length + 1 ? -2 : 0
);
Note that this is not necessarily more readable, it just takes up less space.
You can get it a bit more succinct by using the fact that your if clauses logically imply each other partly.
if e.shiftKey is true you change something if this.idx is 0 or more and if e.shiftKey is false you change something only if this.idx < trapFocus.length + 1:
let offset = 0;
if (e.shiftKey){
if (this.idx >= 0) (this.idx ? offset = -1 : offset = 2)
} else {
if (this.idx < trapFocus.length + 1)
(this.idx < trapFocus.length - 1 ? offset = 1 : offset = -2)
}
this.idx += offset;
It is not necessarily much more readable.

Simple Calculator: Value in Function not defined but is listed in condition

After some extensive reading and help from the community I have started to create formulae in the form of calculators to practice my knowledge using my real world influences. I have created this calculator and added an additional condition to the equation but now the working calculator can't define a function which had worked previously.
The value is defined and given at the beginning of the function so I don't understand why it is not longer defined when adding the condition.
var lsaForm = document.forms["lsacalc"],
days = document.getElementById('days'),
rlsa = document.getElementById("rlsa"),
dayRateLsa = document.getElementById("rlsa"),
rddlsa = document.getElementById("rddlsa"),
tlsa = document.getElementById('tlsa');
function lsaupdateTotals() {
var x = rlsa.value;
var y = dayRateLsa.value;
if (x == 1 || (y > 1 && y < 281)) {
rdlsa = 7.45;
} else if (x == 2 || (y > 280 && y < 461)) {
rdlsa = 11.65;
} else if (x == 3) {
rdlsa = 15.85;
} else if (x == 4) {
rdlsa = 17.40;
} else if (x == 5) {
rdlsa = 18.73;
}
let total = days.value * rdlsa;
rddlsa.innerHTML = `Daily rate of LSA £${rdlsa}`;
tlsa.innerHTML = `Total LSA Enitlement £${total}`;
}
I have resolved this by applying the rest of the conditions throughout the function, the console returned an error but unspecified. Theoretically I think that the value of 'RDLSA' returned different with the additional conditions.
function lsaupdateTotals() {
var x = rlsa.value;
var y = dayRateLsa.value;
if (x = 1 || (y > 1 && y < 281)) {
rdlsa = 7.45;
} else if (x = 2 || (y > 280 && y < 461)) {
rdlsa = 11.65;
} else if (x = 3 || (y > 461 && y < 640)) {
rdlsa = 15.85;
} else if (x = 4 || (y > 641 && y < 821)) {
rdlsa = 17.40;
} else if (x = 5 || (y > 821 && y < 1001)) {
rdlsa = 18.73;
} else if (x = 6 || (y > 1001 && y < 1181)) {
rdlsa = 20.07;
} else if (x = 7 || (y > 1181 && y < 1360)) {
rdlsa = 21.39;
} else if (x = 8 || (y > 1361 && y < 1540)) {
rdlsa = 23.40;
} else if (x = 9 || (y > 1541 && y < 1720)) {
rdlsa = 24.75;
} else if (x = 10 || (y > 1721 && y < 1901)) {
rdlsa = 26.09;
} else if (x = 11 || (y > 1901 && y < 2081)) {
rdlsa = 27.42;
} else if (x = 12 || (y > 2081 && y < 2261)) {
rdlsa = 28.77;
} else if (x = 13 || (y > 2261 && y < 2241)) {
rdlsa = 30.09;
} else if (x = 14 || (y > 2241 && y < 2801)) {
rdlsa = 31.43;
} else if (x = 15 || (y > 2801 && y < 3160)) {
rdlsa = 32.75;
} else if (x = 16 || y < 3161) {
rdlsa = 34.07;
};
let total = days.value * rdlsa;
rddlsa.innerHTML = `Daily rate of LSA £${rdlsa}`;
tlsa.innerHTML = `Total LSA Enitlement £${total}`;
}

Stuck programming Conway's "Game of Life" in JS

We have to program a JavaScript version of Conway's Game of Life for a school project, but we're stuck on looping the edges. The whole thing works fine, but the function that calculates the number of neighbors doesn't work on the cells that are on the edges (because it has to evaluate values outside of the array, which are undefined). We've tried several options, but they all alter the functionality of the rest of the program.
What should we add for it to work on the edges of the grid?
var totalNeighbors = function(x, y) {
var total = 0;
if (x > 0 && cells[(x - 1)][y] == 1) {
total++;
}
if (x < (width - 1) && cells[x + 1][y] == 1) {
total++;
}
if (y > 0 && cells[x][y - 1] == 1) {
total++;
}
if (y < (height - 1) && cells[x][y + 1] == 1) {
total++;
}
if (y > 0 && x > 0 && cells[x - 1][y - 1] == 1) {
total++;
}
if (y > 0 && x < (width - 1) && cells[x + 1][y - 1] == 1) {
total++;
}
if (y < (height - 1) && x > 0 && cells[x - 1][y + 1] == 1) {
total++;
}
if (y < (height - 1) && x < (width - 1) && cells[x + 1][y + 1] == 1) {
total++;
}
return total;
};
Thanks!
I'd go with something more like this:
As you can see, I refactored a little bit.
var isvalid = function(x, y) {
/*
* This returns 1 if cells[x][y] == 1.
* Otherwise, we return 0.
* NOTE: If cells[x, y] is out of bounds, we return 0.
* GLOBALS USED: cells, width, and height.
*/
//This returns true if (index < size && index >= 0)
//Used to check that index is not an invalid index.
var inbounds = function (size, index) {
return (index >= 0 && index < size);
};
//given point is out of bounds
if (!inbounds(width, x) || !inbounds(height, y)) {
return 0;
}
//everything is good
return (cells[x][y] === 1) ? 1 : 0;
};
var totalNeighbors = function(x, y) {
var total = 0;
//cells[x-1][y]
total += isvalid(x-1, y);
//cells[x + 1][y]
total += isvalid(x+1, y);
//cells[x][y - 1]
total += isvalid(x, y-1);
//cells[x][y + 1]
total += isvalid(x, y+1);
//cells[x - 1][y - 1]
total += isvalid(x-1, y-1);
//cells[x + 1][y - 1]
total += isvalid(x+1, y-1);
//cells[x - 1][y + 1]
total += isvalid(x-1, y+1);
//cells[x + 1][y + 1]
total += isvalid(x+1, y+1);
return total;
};
PS: Your original code sample is 37 lines without comments. My code sample is 52 lines with comments and 33 lines without comments.
As near as I can figure, this way is cleaner and shorter. ;)

howto convert a number to a clever number with specific length and k, m, b

for example I have this number:
1,234,567.89
And I want to convert this number to a number with a specific length like these:
1M
01M
1.2M
1.23M
1.234M
1.2346M
1.23457M
1,234,568
01,234,568
1,234,567.9
1,234,567.89
Is there any javascript function, plugin or something for doing this in such a way (with K, M, B...)?
I don't understand your downvotes because this a not a duplicated question und I found NOTHING similar. So i made it by myself and it works ;)
function number(num, size) {
var s = num;
var l1 = s.toString().length;
if (l1 > size && num > 1) s = Math.floor(num);
var l2 = s.toString().length;
if (l2 > size) {
if (num >= 1e3 && num < 1e6) {
s = num / 1e3;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'k';
} else if (num >= 1e6 && num < 1e9) {
s = num / 1e6;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'M';
} else if (num >= 1e9 && num < 1e12) {
s = num / 1e9;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'G';
} else if (num >= 1e12 && num < 1e15) {
s = num / 1e12;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'T';
} else if (num >= 1e15 && num < 1e18) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'P';
} else if (num >= 1e18 && num < 1e21) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'E';
} else if (num >= 1e21 && num < 1e24) {
s = num / 1e21;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Z';
} else if (num >= 1e24 && num < 1e27) {
s = num / 1e24;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Y';
}
}
var l3 = s.toString().length;
if (l3 > size) s = '-';
var s = s.toString();
while (s.length < size) s = s.charAt(0) == '-' ? '-' + s : '0' + s;
var startZeros = /^(0)\1+/.exec(s),
startZerosCount = (startZeros != null) ? startZeros[0].length : 0,
decimalCount = (num.toString().split('.')[1] || []).length;
if (startZerosCount >= 2 && decimalCount > 0 && s.indexOf('.') < 0) {
var decimals = num.toString().split('.')[1],
movedDigits = Math.min(startZerosCount, decimalCount),
lastChar = s.substring(s.length - 1);
if (isNaN(lastChar)) {
s = s.substring(0, s.length - 1);
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
s += lastChar;
} else {
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
}
}
return s;
}
The output for 784432432.9999 is:
-
--
---
784M
0784M
784.4M
784.43M
784.432M
784432432
0784432432

Categories

Resources