How do I determine the efficiency of mouse movement from Point A to Point B in Javascript? - javascript

I am trying to create an analytical program which keeps track of user mouse movement on a website and stores the data in a DB. Here is where I am stuck:
Assuming the mouse is always starting at the middle of the screen, and the user is instructed to move it to a particular element, how do I determine the efficiency and accuracy of that movement. I need to keep in mind the duration from start of hovering till the click, but I want to also include the hovering path of the mouse.
A perfect score would be a perfect line from Point A to Point B in x seconds, how do I determine the score of a curved path in 2x seconds, or an instance where the path goes in the wrong direction before proceeding to Point B? Are there any algorithms in existence?
Thanks for your help!

Here is a JSFiddle that I created. Click on the START box and then click on the FINISH box. Hopefully this will help you get started.
var start = false;
var start_time,end_time;
var points = [];
$("#start").click(function() {
start = true;
points = [];
start_time = Date.now();
});
$("#finish").click(function() {
start = false;
distance = travelledDistance();
time = (Date.now() - start_time)/1000;
var center_x_start = $("#start").offset().left + $("#start").width() / 2;
var center_y_start = $("#start").offset().top + $("#start").height() / 2;
var center_x_finish = $("#finish").offset().left + $("#finish").width() / 2;
var center_y_finish = $("#finish").offset().top + $("#finish").height() / 2;
var straight_distance = Math.round(Math.sqrt(Math.pow(center_x_finish - center_x_start, 2) + Math.pow(center_y_finish - center_y_start, 2)));
$("#time").text(+time+"s");
$("#distance").text(distance+"px");
$("#straight_distance").text(straight_distance+"px");
});
$(document).mousemove(function( event ) {
if(!start)
return;
points.push(event.pageX + "," + event.pageY);
});
function travelledDistance(){
var distance = 0;
for (i = 0; i < points.length - 1; i++) {
start_point = points[i].split(",");
end_point = points[i+1].split(",");
distance += Math.round(Math.sqrt(Math.pow(end_point[0] - start_point[0], 2) + Math.pow(end_point[1] - start_point[1], 2)));
}
return distance;
}
UPDATE
I made a new version here. Now you can drag the targets to check the different results.

Related

How to realistically simulate car steering physics

I'm making a car simulation in Javascript and I am using this website to help me with the physics: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html
The current progress of the simulation can be seen on my website:
https://cloudynet.tk/projects/car-sim/code.html
The problem I have is with the car steering physics. I have managed to get the low-speed steering to work correctly but the high-speed steering (where lateral forces are introduced) is very hard to get right. I understand how slip angles influence the lateral force but in my simulation, it is not working very well. I'm wondering if the implementation of the lateral force is correct or is there something wrong with the code? Also, I don't quite understand if the longitudinal force and the lateral force affects a single velocity vector or is separated into two "directional" vectors.
Here's my current physics function (whole code can be seen on the website):
applyPhysics() {
// Get car direction vector
let direction = new Vector(1, 0);
direction = Vector.rotate(direction, this.carAngle);
// LONGITUDINAL FORCES
// Traction forces
let tractionForce = direction.copy(); // Traction force (engine power)
if (this.engineForce) {
tractionForce.mult(this.engineForce);
}
else if (this.brakingForce) {
tractionForce.mult(-this.brakingForce);
}
// Frictional forces
let dragForce = this.velocity.copy(); // Air resistance force
dragForce.mult(this.velocity.getMag())
dragForce.mult(-this.drag);
let rollingResistanceForce = this.velocity.copy(); // Rolling resistance force (friction with ground)
rollingResistanceForce.mult(-this.rrDrag);
let netLongitudinalForce = tractionForce.copy(); // Total longitudinal force
netLongitudinalForce.add(dragForce)
netLongitudinalForce.add(rollingResistanceForce);
// Calculate acceleration
this.acceleration = netLongitudinalForce.copy();
this.acceleration.div(this.mass);
if (this.acceleration.getMag() < 0.001)
this.acceleration = new Vector();
// Calculate velocity
let accelerationDelta = this.acceleration.copy();
accelerationDelta.mult(dt);
this.velocity.add(accelerationDelta);
this.velDir = this.velocity.getDir();
this.sideslipAngle = this.carAngle - this.velDir; // Calculate side slip angle
if (this.speed > 20) { // High speed-turning
// LATERAL FORCES
let peakSlipAngle = 5;
// Calculate slip angle for back wheel
var c = this.wheels.baseline/2;
var omegaC = this.angularVelocity*c;
var longV = Math.cos(this.carAngle) * this.velocity.getMag();
var latV = Math.sin(this.carAngle) * this.velocity.getMag();
this.wheels.back.slipAngle = Math.atan(((latV - omegaC)/Math.abs(longV)) || 0);
var backSlipDeg = deg(this.wheels.back.slipAngle)
this.wheels.back.lateralForce = 5000*Math.sign(this.wheels.back.slipAngle);
if (backSlipDeg < peakSlipAngle && backSlipDeg > -peakSlipAngle) {
this.wheels.back.lateralForce = 5000*backSlipDeg/peakSlipAngle;
} else {
this.wheels.back.lateralForce = 5000*(1-((Math.abs(backSlipDeg)-peakSlipAngle)/500))*Math.sign(this.wheels.back.slipAngle);
}
// Calculate slip angle for front wheel
var b = this.wheels.baseline/2;
var omegaB = this.angularVelocity*b;
var longV = Math.cos(this.wheels.front.slipAngle) * this.velocity.getMag();
var latV = Math.sin(this.wheels.front.slipAngle) * this.velocity.getMag();
this.wheels.front.slipAngle = Math.atan((((latV - omegaB)/Math.abs(longV)) || 0)-this.steeringAngle*Math.sign(longV));
var frontSlipDeg = deg(this.wheels.front.slipAngle);
this.wheels.front.lateralForce = 5000*Math.sign(this.wheels.front.slipAngle);
if (frontSlipDeg < peakSlipAngle && frontSlipDeg > -peakSlipAngle) {
this.wheels.front.lateralForce = 5000*frontSlipDeg/peakSlipAngle;
} else {
this.wheels.front.lateralForce = 5000*(1-((Math.abs(frontSlipDeg)-peakSlipAngle)/500))*Math.sign(this.wheels.front.slipAngle);
}
// Calculate cornering force
this.corneringForce = this.wheels.back.lateralForce + Math.cos(this.steeringAngle) * this.wheels.front.lateralForce;
// Calculate centripetal force
this.centripetalForce = this.mass * (this.velocity.getMag() ** 2) / this.wheels.baseline/Math.sin(this.steeringAngle);
var lateralDirection = new Vector(0, -1);
lateralDirection = Vector.rotate(lateralDirection, this.carAngle);
let lateralForce = lateralDirection.copy();
lateralForce.mult(this.corneringForce);
this.latAcceleration = lateralForce.copy();
this.latAcceleration.div(this.mass);
if (this.latAcceleration.getMag() < 0.001)
this.latAcceleration = new Vector();
let latAccelerationDelta = this.latAcceleration.copy();
latAccelerationDelta.mult(dt);
this.latVelocity.add(latAccelerationDelta);
// Calculate position
let latVelocityDelta = this.latVelocity.copy();
latVelocityDelta.mult(dt);
this.pos.add(latVelocityDelta);
} else {
this.velocity = Vector.rotate(this.velocity, this.carAngle - this.velDir); // Correct velocity based on car orientation
}
// Calculate position
let velocityDelta = this.velocity.copy();
velocityDelta.mult(dt);
this.pos.add(velocityDelta);
// Calculate speed
this.speed = this.velocity.getMag();
}
I believe the problem is with the lines regarding the slip angles. I would look over the script carefully or ctrl f to find where you typed Math.sign rather than Math.sin(). I'm not sure if this is the problem but it's something I noticed looking over your code. I'm working on a basic drifting game with javascript and it requires a lot of the same physics as your project.
Hopefully, I was able to help

Javascript enemies follow player

I am coding a lil js game for a university project.
I have a 2d map and I can move my player with arrows. Enemies are spawned every 5 seconds and they are guided by the function:
enemy.updatePosition = function() {
if(enemy.isAttacking === false) {
var diffX = Math.floor(player.x - enemy.x);
var diffY = Math.floor(player.y - enemy.y);
//security distance by player --> superEnemy type 1 uses arrows
var distance = getDistanceBetweenEntities(player, enemy);
var gap = 20;
enemy.pressingRight = diffX > gap;
enemy.pressingLeft = diffX < -gap;
enemy.pressingDown = diffY > gap;
enemy.pressingUp = diffY < -gap;
enemy.isStopped = false;
if(enemy.speedX < 0)
enemy.speedX = - enemy.speedX;
if(enemy.speedY < 0)
enemy.speedY = - enemy.speedY;
//bumpers check if hitting a wall or end of map
var rightBumper = {x:enemy.x + 15, y:enemy.y};
var leftBumper = {x:enemy.x - 15, y:enemy.y};
var upBumper = {x:enemy.x, y:enemy.y - 25};
var downBumper = {x:enemy.x, y:enemy.y + 20};
if(currentMap.isPositionWall(rightBumper)) {
enemy.x -= 1;
} else {
if(enemy.pressingRight)
enemy.x += enemy.speedX;
}
if(currentMap.isPositionWall(leftBumper)) {
enemy.x += 1;
} else {
if(enemy.pressingLeft)
enemy.x -= enemy.speedX;
}
if(currentMap.isPositionWall(downBumper)) {
enemy.y -= 1;
} else {
if(enemy.pressingDown)
enemy.y += enemy.speedY;
}
if(currentMap.isPositionWall(upBumper)) {
enemy.y += 1;
} else {
if(enemy.pressingUp)
enemy.y -= enemy.speedY;
}
//set position again if the center of the draw
//of enemy goes out of map's limits
if(enemy.x < enemy.width/2)
enemy.x = enemy.width/2;
if(enemy.x > currentMap.width - enemy.width/2)
enemy.x = currentMap.width - enemy.width/2;
if(enemy.y < enemy.height/2)
enemy.y = enemy.height/2;
if(enemy.y > currentMap.height - enemy.height/2)
enemy.y = currentMap.height - enemy.height/2;
}
}
}
So my enemies follow the player with the values of diffX and diffY. Each enemy has it own speedX and speedY, something like:
var random = 1 + Math.random()*7; //from 1 to 8
enemy.speedX = random;
enemy.speedY = random;
The result is that enemies start to overlap, expecially when they are performing an attack(x and y don't changes during attack). Is there a simple way to avoid that without checking a lot of collision? Thanks everyone
There are more options for you, but here is one simple collision detection.
First you will need to make every enemy unique like giving everyone of them a unique name. This doesn't need to be complicated just like enemy1, enemy2, .... enemy223. You can do it at the point where you spawn the enemy, like this:
enemy['name'] = 'enemy' + i++;
so you can access it like this:
enemy.name;
Important: you should write some kind position that updates everytime the 'enemy' changes position or every tick.
enemy['position'] = enemy.x+','+enemy.y;
make an array into that you can write the positions of every enemy. I know this is not the best option but it's simple and will work for now.
var pstns = [];
After that write every enemy into the array (just do it at spawn). I would like to mention that the following is not good practice.
var pstnsObj = {};
pstnsObj[enemy.name] = enemy.position;
pstns.push(pstnsObj);
Next you need to update the position in the array every tick with every enemy. This is only one example you can do it multiple ways or even automate this process.
function updatePstns(id, position){
pstns[id][Object.keys(pstns[id])[0]] = position;
//just in case:
return pstns;
}
//updating first enemy:
updatePstns(0, enemy.position);
now for the collision:
function checkCollision(){
var count = 0;
pstns.forEach(function(e){
for(i=0; i<pstns.length; i++){
if(pstns[e][Object.keys(pstns[e])[0]] == pstns[i][Object.keys(pstns[i])[0]]){
count++;
}
}
if(count > 1){
console.log('enemy ' + pstns[e] + 'collides with ' + count + 'enemies');
}
});
}

How to trigger a function repeatedly

I am working on a randomising function for a game in javascript and jquery. I have written this to randomise the position of a square in a 8x8x64px grid, and give the player a point when their character moves over it. The function works once, but wont repeat.
The relevant script
Every time the player moves it searches for
if (xNum==ptX && yNum==ptY) {
getPoint();
pointRand();
}
yNum and xNum is the player's coordinates and ptY and ptX is the point's. Movement occurs on keyUp for the arrow keys, and the if is also executed then.
Corresponding functions
//Score
var ptAllow = true;
var pt = 0;
var ptX = 7;
var ptY = 7;
var yPt = ptX*64+"px";
var xPt = ptY*64+"px";
function getPoint() {
if (ptAllow == true) {
pt++;
document.getElementById("scoreCounter").innerHTML = "score: "+pt;
document.getElementById("scoreFin").innerHTML = "score: "+pt;
}
}
function pointRand() {
ptX = Math.floor(Math.random() * 8) + 1;
ptY = Math.floor(Math.random() * 8) + 1;
ptX--;
ptY--;
yPt = ptX*64+"px";
xPt = ptY*64+"px";
$("#point").animate({"left": xPt, "top": yPt}, 100);
}
Like I said, It works perfectly the first time you move over a point, but after that nothing happens. . ptAllow is set to false once the player hits an obstacle, and the game is over.
Edit: There are no errors in the browser console, and the reason for adding and subtracting in pointRand() is that math.floor does not seem to work with a lowest value of zero.

Three.js performance very slow using onMouseMove with RayCaster

I'm building an application in three.js, however I'm having real problems with performance. This part of the application is based upon the Voxel Painter example. In my version, the user clicks on a cell to begin placement, drags the cursor to where they wish to end placement, and clicks to end.
function onDocumentMouseMove(event) {
//set up mouse and raycaster
event.preventDefault();
mouse.set((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1);
raycaster.setFromCamera(mouse, camera);
switch (buildMode) {
case buildModes.CORRIDOR:
scene.add(rollOverFloor);
var intersects = raycaster.intersectObjects(gridObject);
if (intersects.length > 0) {
var intersect = intersects[0];
if (beginPlace == true) {
//store the intersection position
var endPlace = new THREE.Vector3(0, 0, 0);
endPlace.copy(intersect.point).add(intersect.face.normal);
endPlace.divideScalar(step).floor().multiplyScalar(step).addScalar(step / step);
endPlace.set(endPlace.x, 0, endPlace.z);
corridorDrag(endPlace);
}
//if user hasn't begun to place the wall
else {
//show temporary wall on grid
rollOverFloor.position.copy(intersect.point).add(intersect.face.normal);
rollOverFloor.position.divideScalar(step).floor().multiplyScalar(step).addScalar(step / step);
rollOverFloor.position.set(rollOverFloor.position.x, 0, rollOverFloor.position.z);
}
}
break;
}
render();
}
The code above is called when the user moves the mouse (there are many buildmodes in the main application, but I have not included them here). This function simply gets a start and end point, the corridorDrag() function fills in the cells between the start and end points:
function corridorDrag(endPlace) {
deleteFromScene(stateType.CORRIDOR_DRAG);
var startPoint = startPlace;
var endPoint = endPlace;
var zIntersect = new THREE.Vector3(startPoint.x, 0, endPoint.z);
var xIntersect = new THREE.Vector3(endPoint.x, 0, startPoint.z);
var differenceZ = Math.abs(startPlace.z - zIntersect.z);
var differenceX = Math.abs(startPlace.x - xIntersect.x);
var mergedGeometry = new THREE.Geometry();
for (var i = 0; i <= (differenceZ / step); i++) {
for (var j = 0; j <= (differenceX / step); j++) {
var x = startPlace.x;
var y = startPlace.y;
var z = startPlace.z;
if (endPoint.x <= (startPlace.x )) {
if (endPoint.z <= (startPlace.z)) {
x = x - (step * j);
z = z - (step * i);
}
else if (endPoint.z >= (startPlace.z)) {
x = x - (step * j);
z = z + (step * i);
}
} else if (endPoint.x >= (startPlace.x)) {
if (endPoint.z <= (startPlace.z)) {
x = x + (step * j);
z = z - (step * i);
}
else if (endPoint.z >= (startPlace.z)) {
x = x + (step * j);
z = z + (step * i);
}
}
floorGeometry.translate(x, y, z);
mergedGeometry.merge(floorGeometry);
floorGeometry.translate(-x, -y, -z);
}
}
var voxel = new THREE.Mesh(mergedGeometry, tempMaterial);
voxel.state = stateType.CORRIDOR_DRAG;
scene.add(voxel);
tempObjects.push(voxel);
}
Firstly, the deleteFromScene() function removes all current highlighted cells from the scene (see below). The code then (I believe), should create a number of meshes, depending on the start and end points, and add them to the scene.
function deleteFromScene(state) {
tempObjects = [];
var i = scene.children.length;
while (i--) {
if (scene.children[i].state != undefined)
if (scene.children[i].state == state)
scene.children.splice(i, 1);
}
}
As I said, it is very, very slow. It also appears to be adding an obscene amount of vertices to the renderer, as seen in the WebGLRenderer stats window. I have no idea why it's adding so many vertices, but I'm assuming that's why it's rendering so slowly.
The application can be viewed here - the problem can be seen by clicking on one cell, dragging the cursor to the other end of the grid, and observing the time taken to fill in the cells.
Thank you in advance, this really is a last resort.
A few years ago Twitter put out an update. In this update they had just introduced infinite scrolling and on the day of its release the update was crashing users browsers. Twitter engineers did some investigating and found that the crashes were the result of the scroll event firing hundreds of times a second.
Mouse events can fire many MANY times a second and can cause your code to execute too often, which slows down the browser and (in many cases) crashes it. The solution for Twitter (and hopefully you) was simple: Poll your event.
Inside your mousemove event handler check that it has been some number of milliseconds since the last move event.
var lastMove = Date.now();
function onDocumentMouseMove(event) {
if (Date.now() - lastMove < 31) { // 32 frames a second
return;
} else {
lastMove = Date.now();
}
// your code here
}
I hope that helps!

move div smoothly with javascript/jquery and an array of pos

I'm looking for a way to move a div from an array of position with javascript/jquery.
I have trying to do it with jquery.animate but he moved the div with a pause at each iteration of my array.
That could be something like move the div from 0,0 to 120px,230px passing by the 23px,35px;45px,50px etc...
That is for moving an game character on a Tile map
So as requested, some bit of code
First you have a global timer that call a function at short interval to see if it have any action to execute.
In this loop a routine look if some mobile tiles are waiting of any mouvement.
Mobiles are declared as Object class and have a sub function that do the deplacement like that
setPos:function(coord){
var pos = jQuery("#"+this.id).position();
var x = (coord[0] - 32 + this.screenOffX + this.xOffset) - pos.left;
var y =(coord[1] + this.yOffset) - pos.top;
//this.stopAnimation();
//this.startAnimation(this.walkingAnimation);
jQuery("#"+this.id).animate({
left: '+='+ x,
top: '+='+ y
}, 33, function() {
// Animation complete.
});
},
That is a bit messy cause i trying a lot of thing to do the smooth movement that i'm looking for.
so setPos is calling in another place like that
stepMobile:function(mobile){
var wp;/*TEST*/
mobile.changeState("idle");
var ind = mobile.getWayPointIndex();
while(ind < (mobile.getWayPoints()).length - 1){
if (ind < (mobile.getWayPoints()).length - 1) {
wp = (mobile.getWayPoints())[ind + 1];
if (getTime() > wp.time) {
mobile.setWayPointIndex(ind + 1);
ind = ind +1;
}
}
wp = (mobile.getWayPoints())[ind];
var x;
var y = 0;
var z;
x = this.tileWidth * (wp.getTile()).getCol();
z = this.tileHeight * (wp.getTile()).getRow();
var elapsed = getTime() - wp.getTime();
console.log(elapsed);
if (ind == (mobile.getWayPoints()).length - 1) {
console.log('checkForOnStopEvent()');
} else {
//x += 1 * mobile.getWalkSpeed() * mobile.getCosAngle();
//z += 1 * mobile.getWalkSpeed() * mobile.getSinAngle();
}
var coord = this.mapToScreen(x, y, -z);
mobile.setPos(coord);
ind = mobile.getWayPointIndex();
}
},
Again lot of junk code here cause i literally burned my brain but i didn't get any good result.
And you have that global function that run this function over all mobiles waiting for deplacement.

Categories

Resources