Skip to content

Commit

Permalink
add tweening for big servo jumps for realism
Browse files Browse the repository at this point in the history
  • Loading branch information
bacalj committed Mar 28, 2024
1 parent ebba738 commit 6280a14
Showing 1 changed file with 17 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useRef, useState } from "react";
import classNames from "classnames";
import { ISimulation, ISimulationProps } from "../simulation-types";
import { iconUrl, kPotentiometerKey, kServoKey, kSignalKey
Expand All @@ -14,33 +14,44 @@ import MinimizeIcon from "./assets/minimize-arduino.svg";

import "./potentiometer-servo.scss";


export const kPotentiometerServoKey = "potentiometer_chip_servo";

const potVisibleOffset = 135;
const servoVisibleOffset = 90;
const minPotAngle = 0;
const maxPotAngle = 270;
const minServoAngle = 0;
const maxServoAngle = 180;
const minResistReading = 0;
const maxResistReading = 1023;

const kPotAngleKey = "pot_angle_key";
const kResistReadingKey = "resist_reading_key";
const kServoAngleKey = "servo_angle_key";

function getTweenedServoAngle(realValue: number, lastVisibleValue: number) {
const delta = realValue - lastVisibleValue;
const steps = 5;
const maxDelta = 40;
if (Math.abs(delta) > maxDelta) {
return (lastVisibleValue + Math.sign(delta) * steps);
}
return realValue;
}

function PotentiometerAndServoComponent({ frame, variables }: ISimulationProps) {
const [collapsed, setMinimized] = useState(false);
const tweenedServoAngle = useRef(0);
const lastTweenedAngle = tweenedServoAngle.current;

const potAngleVar = findVariable(kPotAngleKey, variables);
const potAngleBaseValue = potAngleVar?.currentValue ?? 0;
const visiblePotAngle = potAngleBaseValue - 135; // We use 0 - 270 degrees, but we want to render visible -135 - 135
const visiblePotAngle = potAngleBaseValue - potVisibleOffset;
const potRotationString = `rotate(${visiblePotAngle ?? 0}deg)`;

const servoAngleVar = findVariable(kServoAngleKey, variables);
const servoAngleBaseValue = servoAngleVar?.currentValue ?? 0;
const visibleServoAngle = servoAngleBaseValue - 90; // We use 0 - 180 degrees, but we want to render visible -90 - 90
const servoRotationString = `rotate(${visibleServoAngle}deg)`;
tweenedServoAngle.current = getTweenedServoAngle(servoAngleBaseValue, lastTweenedAngle);
const servoRotationString = `rotate(${tweenedServoAngle.current - servoVisibleOffset}deg)`;

const potServoClasses = classNames('pot-servo-component', { collapsed, "expanded": !collapsed });

Expand Down

0 comments on commit 6280a14

Please sign in to comment.