velocity!!!!

This commit is contained in:
Ben Kyd
2021-04-04 03:13:47 +01:00
parent fe9005f892
commit f1bb2036bb
2 changed files with 48 additions and 6 deletions

View File

@@ -3,8 +3,8 @@ function localeString(code)
{
let strings = JSON.parse(localStorage.getItem('locale-strings'));
let whatstring = strings[code];
if (!whatstring || whatstring == '') whatstring = strings['en'];
let locale = whatstring[localStorage.getItem('locale')];
if (!locale || locale == '') locale = whatstring['en'];
return locale;
}

View File

@@ -15,6 +15,12 @@ document.querySelectorAll('piece').forEach(element => {
});
let selectedElement = {};
let lastCoords = { x: 0, y: 0 };
function magnitude(v)
{
return Math.sqrt((v.x * v.x) + (v.y * v.y));
}
function mouseDown(event, element)
{
@@ -35,6 +41,7 @@ function mouseDown(event, element)
// move to the centre of the mouse to simulate pickup
selectedElement.style.left = `${window.scrollX + (event.clientX - 20)}px`;
selectedElement.style.top = `${window.scrollY + (event.clientY - 20)}px`;
selectedElement.velocity = {x: 0, y: 0};
}
function mouseMove(event)
@@ -46,20 +53,55 @@ function mouseMove(event)
if (event.type === 'touchmove')
event = event.changedTouches[0];
// do some fun velocity stuff
selectedElement.velocity.x = (window.scrollX + (event.clientX - 20)) - lastCoords.x;
selectedElement.velocity.y = (window.scrollY + (event.clientY - 20)) - lastCoords.y;
selectedElement.style.left = `${window.scrollX + (event.clientX - 20)}px`;
selectedElement.style.top = `${window.scrollY + (event.clientY - 20)}px`;
lastCoords.x = window.scrollX + (event.clientX - 20);
lastCoords.y = window.scrollY + (event.clientY - 20);
}
}
function slidePiece(piece)
{
const id = setInterval(() =>
{
if (magnitude(piece.velocity) <= 1)
{
piecePlaced(piece);
clearInterval(id);
return;
}
piece.style.left = `${piece.getBoundingClientRect().left + piece.velocity.x}px`;
piece.style.top = `${piece.getBoundingClientRect().top + piece.velocity.y}px`;
piece.velocity.y *= 0.95;
piece.velocity.x *= 0.95;
}, 16)
}
function mouseUp(event)
{
event.preventDefault();
if (event.toElement.localName !== 'score') return;
event.preventDefault();
if (selectedElement.pointerEvents != 'initial')
{
piecePlaced(selectedElement);
selectedElement.pointerEvents = 'initial';
console.log(magnitude(selectedElement.velocity));
if (magnitude(selectedElement.velocity) <= 1)
{
piecePlaced(selectedElement);
selectedElement.pointerEvents = 'initial';
}
else
{
slidePiece(selectedElement);
selectedElement.pointerEvents = 'initial';
}
}
}