From e88c3ab2c146214a0173804ea206f807ff43be53 Mon Sep 17 00:00:00 2001 From: Cristian Marcelo de Picciotto Date: Sun, 13 Oct 2024 16:07:50 -0300 Subject: [PATCH] fix: adjust friction calculation [#1] --- docs/js/core/car.js | 12 +++++++----- docs/js/core/car/control.js | 15 ++++++--------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/docs/js/core/car.js b/docs/js/core/car.js index 6764926..4cafdc3 100644 --- a/docs/js/core/car.js +++ b/docs/js/core/car.js @@ -66,8 +66,8 @@ export default class Car { centerY, width, height, - friction = 1, - force = 100, + friction = 50, + force = 200, control = new Control(), ) { this.centerX = centerX @@ -144,12 +144,14 @@ export default class Car { * until it reaches `0`. At that moment, the friction disappears */ #applyFriction(t) { - if (Math.abs(this.friction) > Math.abs(this.velocity)) { + const dragEffect = this.friction * t + + if (dragEffect >= Math.abs(this.velocity)) { this.velocity = 0 } else if (this.velocity > 0) { - this.velocity -= this.friction * t + this.velocity -= dragEffect } else if (this.velocity < 0) { - this.velocity += this.friction * t + this.velocity += dragEffect } } diff --git a/docs/js/core/car/control.js b/docs/js/core/car/control.js index 9c07e2b..300280e 100644 --- a/docs/js/core/car/control.js +++ b/docs/js/core/car/control.js @@ -59,7 +59,7 @@ export default class Control { * @param {number} friction * @param {number} torque */ - constructor(friction = 0, torque = 20) { + constructor(friction = 5, torque = 20) { this.friction = friction this.torque = torque @@ -91,12 +91,14 @@ export default class Control { * until it reaches `0`. At that moment, the friction disappears */ #applyFriction(t) { - if (Math.abs(this.friction) > Math.abs(this.omega)) { + const dragEffect = this.friction * t + + if (dragEffect >= Math.abs(this.omega)) { this.omega = 0 } else if (this.omega > 0) { - this.omega -= this.friction * t + this.omega -= dragEffect } else if (this.omega < 0) { - this.omega += this.friction * t + this.omega += dragEffect } } @@ -174,9 +176,6 @@ export default class Control { * Because `torque` is an angular force, * and every force causes acceleration, then * the `alpha`/angular acceleration is removed - * @todo For now, we are note going to use friction, and the - * `omega`/angular velocity will be reduce immediately to `0` - * without any force acting on it */ #addKeyUpListener() { window.addEventListener('keyup', (e) => { @@ -192,13 +191,11 @@ export default class Control { case 'ArrowLeft': this.left = false this.alpha = 0 - this.omega = 0 break case 'ArrowRight': this.right = false this.alpha = 0 - this.omega = 0 break } })