Сдеалй так, чтобы число и график сами по себе постоянно немного прыгали, не отходя далеко от реального числа, чтобы это было реалистичнее, а также, чтобы график двигался сам по себе
Чтобы сделать отображение уровня радиации более реалистичным, добавив небольшие случайные колебания как для числа, так и для графика, необходимо внести изменения в файл app.js. Эти изменения включают добавление небольших случайных изменений к текущему уровню радиации и обеспечение плавного обновления графика.
Вот пошаговое руководство по внесению необходимых изменений:
Добавление базового уровня радиации:
Введите новую переменную baseRadiationLevel, которая будет представлять основной уровень радиации, установленный пользователем через слайдер или гироскоп.
Текущий отображаемый уровень радиации (radiationLevel) будет немного отклоняться от baseRadiationLevel для создания эффекта нестабильности.
Регулярное обновление отображаемого уровня радиации с небольшими колебаниями:
Используйте setInterval для периодического добавления небольшого случайного значения к radiationLevel, обеспечивая тем самым реалистичные колебания.
Убедитесь, что radiationLevel остается в пределах от 0 до 100, чтобы избежать некорректных значений.
Обновление функции updateDisplay:
Модифицируйте функцию updateDisplay таким образом, чтобы она использовала radiationLevel для обновления отображаемого значения и графика.
Изменение обработчиков событий для слайдера и гироскопа:
Убедитесь, что при изменении уровня радиации через слайдер или гироскоп обновляется baseRadiationLevel, а не radiationLevel напрямую.
Ниже приведен полный обновленный код app.js с внесенными изменениями:
javascript
$(document).ready(function () {
let baseRadiationLevel = 0; // Новый базовый уровень радиации
let radiationLevel = 0;
let beepTimeout;
let audioCtx;
let masterGain;
let lfo;
let isAudioInitialized = false;
// Graph Configuration
const graphData = [];
const maxGraphPoints = 100; // Maximum number of data points displayed
const graphUpdateInterval = 100; // Interval in milliseconds for graph updates
const canvas = document.getElementById('radiationGraph');
const ctx = canvas.getContext('2d');
// Function to resize the canvas based on its container
function resizeCanvas() {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
// Initial canvas resize
resizeCanvas();
// Resize the canvas when the window size changes
window.addEventListener('resize', resizeCanvas);
// Function to draw the real-time graph
function drawGraph() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw semi-transparent background
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (graphData.length < 2) return; // Need at least two points to draw
// Determine the color based on the latest value
const latestValue = graphData[graphData.length - 1];
const graphColor = latestValue > 200 ? '#d9534f' : '#00ff00'; // Red if >200, else Green
ctx.strokeStyle = graphColor;
ctx.lineWidth = 2;
ctx.beginPath();
const step = canvas.width / maxGraphPoints;
const maxDisplayValue = 1000; // As per mapping
const minDisplayValue = 50;
graphData.forEach((value, index) => {
const x = index * step;
// Invert Y axis: Higher values appear at the top
const y = canvas.height - ((value - minDisplayValue) / (maxDisplayValue - minDisplayValue)) * canvas.height;
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
}
// Periodically update the graph
setInterval(drawGraph, graphUpdateInterval);
// Function to map slider value (0-100) to display value (50-1000)
function getDisplayValue(level) {
return Math.round(50 + level * 9.5);
}
// Function to update the displayed radiation level and graph data
function updateDisplay() {
const displayValue = getDisplayValue(radiationLevel);
$('#radiationLevel').text(displayValue);
// Update text color based on the display value
if (displayValue > 200) {
$('#radiationLevel').css('color', '#d9534f'); // Red
} else {
$('#radiationLevel').css('color', '#ffffff'); // White
}
// Update graph data
graphData.push(displayValue);
if (graphData.length > maxGraphPoints) {
graphData.shift(); // Remove the oldest data point to maintain the max points
}
}
// Audio Configuration and Functions
const beepDuration = 0.05; // Duration of each beep in seconds
const attackTime = 0.005; // Attack time for ADSR envelope
const decayTime = 0.015; // Decay time for ADSR envelope
// Initialize Audio Context and Nodes
function initAudio() {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Create Master Gain Node
masterGain = audioCtx.createGain();
masterGain.gain.setValueAtTime(0.8, audioCtx.currentTime); // Set master volume
masterGain.connect(audioCtx.destination);
// Create Low-Frequency Oscillator (LFO) for global volume modulation
lfo = audioCtx.createOscillator();
const lfoGain = audioCtx.createGain();
lfo.frequency.setValueAtTime(0.2, audioCtx.currentTime); // LFO frequency: 0.2 Hz
lfoGain.gain.setValueAtTime(0.05, audioCtx.currentTime); // LFO amplitude
lfo.connect(lfoGain);
lfoGain.connect(masterGain.gain);
lfo.start();
isAudioInitialized = true;
}
// Function to start a beep sound
function startBeep() {
if (!isAudioInitialized) return;
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
// Set frequency with slight random variation for a natural sound
const baseFreq = 880;
const variation = (Math.random() - 0.5) * 20; // +/-10 Hz variation
oscillator.frequency.setValueAtTime(baseFreq + variation, audioCtx.currentTime);
oscillator.type = 'sine';
// Configure ADSR envelope for smooth beep
const now = audioCtx.currentTime;
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(0.5, now + attackTime);
gainNode.gain.linearRampToValueAtTime(0, now + attackTime + decayTime);
oscillator.connect(gainNode);
gainNode.connect(masterGain);
oscillator.start();
oscillator.stop(now + beepDuration + decayTime + 0.1); // Ensure oscillator stops after envelope
// Cleanup after beep ends
oscillator.onended = function () {
oscillator.disconnect();
gainNode.disconnect();
};
}
// Function to schedule beeps based on radiation level
function scheduleBeep() {
if (radiationLevel === 0) return;
// Calculate average interval between beeps (lower interval for higher radiation)
const averageInterval = 600 / (radiationLevel + 1); // Adjusted formula for interval
// Introduce randomness to the beep intervals
const jitter = averageInterval * 0.3;
const interval = averageInterval + (Math.random() * jitter * 2 - jitter);
beepTimeout = setTimeout(() => {
// Determine the chance of overlapping beeps based on radiation level
const overlapChance = radiationLevel > 80 ? 0.3 :
radiationLevel > 60 ? 0.2 :
radiationLevel > 40 ? 0.1 : 0.05;
if (Math.random() < overlapChance) {
// Start multiple beeps simultaneously for higher radiation levels
const beepCount = Math.floor(Math.random() * 3) + 1; // 1, 2, or 3 beeps
for (let i = 0; i < beepCount; i++) {
startBeep();
}
} else {
startBeep();
}
scheduleBeep(); // Schedule the next beep
}, interval);
}
// Function to schedule beeps based on display radiation level
function updateBeep() {
clearTimeout(beepTimeout);
if (radiationLevel > 0) {
scheduleBeep();
}
}
// Function для добавления случайных колебаний к radiationLevel
function addRadiationFluctuation() {
// Генерация случайного дельта значения между -2 и +2
const delta = Math.floor(Math.random() * 5) - 2; // -2, -1, 0, +1, +2
let newRadiationLevel = baseRadiationLevel + delta;
// Клэмпинг значения между 0 и 100
newRadiationLevel = Math.max(0, Math.min(100, newRadiationLevel));
radiationLevel = newRadiationLevel;
updateDisplay();
if (isAudioInitialized) {
updateBeep();
}
}
// Установите интервал для добавления колебаний (например, каждые 500 мс)
setInterval(addRadiationFluctuation, 500);
// Event Handler for Slider Input
$('#radiationSlider').on('input', function () {
if (useGyroscope) return; // Ignore slider if gyroscope is active
const newRadiationLevel = parseInt($(this).val());
if (newRadiationLevel !== baseRadiationLevel) {
baseRadiationLevel = newRadiationLevel;
// radiationLevel будет обновляться через колебания
}
});
// Event Handler for Start Button
$('#startButton').click(function () {
if (!isAudioInitialized) {
initAudio();
updateBeep();
$(this).fadeOut(); // Hide the start button after initialization
}
});
// Gyroscope Configuration and Handlers
let useGyroscope = false;
let initialOrientation = null;
let deviceOrientationListener = null;
$('#gyroscopeCheckbox').on('change', function () {
useGyroscope = $(this).is(':checked');
if (useGyroscope) {
// Initialize Gyroscope
if (window.DeviceOrientationEvent) {
// For iOS 13+ devices requiring permission
if (typeof DeviceOrientationEvent.requestPermission === 'function') {
DeviceOrientationEvent.requestPermission()
.then(response => {
if (response === 'granted') {
startGyroscope();
} else {
alert('Доступ к гироскопу отклонен.');
$('#gyroscopeCheckbox').prop('checked', false);
}
})
.catch(() => {
alert('Не удалось получить доступ к гироскопу.');
$('#gyroscopeCheckbox').prop('checked', false);
});
} else {
// For browsers that do not require permission
startGyroscope();
}
} else {
alert('Гироскоп не поддерживается вашим устройством или браузером.');
$('#gyroscopeCheckbox').prop('checked', false);
}
} else {
// Stop Gyroscope
if (deviceOrientationListener) {
window.removeEventListener('deviceorientation', deviceOrientationListener);
deviceOrientationListener = null;
}
initialOrientation = null;
// Re-enable the slider as gyroscope is inactive
$('#radiationSlider').prop('disabled', false);
}
});
// Function to start gyroscope event listening
function startGyroscope() {
initialOrientation = null;
deviceOrientationListener = function (event) {
if (!initialOrientation) {
initialOrientation = {
alpha: event.alpha,
beta: event.beta,
gamma: event.gamma
};
return;
}
// Calculate changes in orientation
let deltaAlpha = Math.abs(event.alpha - initialOrientation.alpha);
let deltaBeta = Math.abs(event.beta - initialOrientation.beta);
let deltaGamma = Math.abs(event.gamma - initialOrientation.gamma);
// Handle angle wrapping around 360 degrees
deltaAlpha = deltaAlpha > 180 ? 360 - deltaAlpha : deltaAlpha;
deltaBeta = deltaBeta > 180 ? 360 - deltaBeta : deltaBeta;
deltaGamma = deltaGamma > 180 ? 360 - deltaGamma : deltaGamma;
// Ignore rotation around Y-axis (gamma)
deltaAlpha = 0;
// Calculate overall deviation
const deviation = Math.sqrt(deltaAlpha * deltaAlpha + deltaBeta * deltaBeta);
// Scale deviation to 0-100 (assuming max 90 degrees)
const scaledDeviation = Math.min(Math.floor((deviation / 90) * 100), 100);
// Update baseRadiationLevel if it has changed
if (scaledDeviation !== baseRadiationLevel) {
baseRadiationLevel = scaledDeviation;
$('#radiationSlider').val(baseRadiationLevel);
// radiationLevel будет обновляться через колебания
}
};
window.addEventListener('deviceorientation', deviceOrientationListener);
// Disable the slider as gyroscope is now active
$('#radiationSlider').prop('disabled', true);
}
// Cleanup Functions on Page Unload
$(window).on('beforeunload', function () {
if (audioCtx) {
audioCtx.close();
}
if (deviceOrientationListener) {
window.removeEventListener('deviceorientation', deviceOrientationListener);
}
});
});
Объяснение внесенных изменений:
Добавление переменной baseRadiationLevel:
Эта переменная хранит основной уровень радиации, установленный пользователем через слайдер или гироскоп.
Переменная radiationLevel теперь используется для отображаемого значения с учетом небольших колебаний.
Регулярные колебания радиации:
Функция addRadiationFluctuation добавляет случайное небольшое значение к baseRadiationLevel, создавая эффект колебаний.
Используется setInterval, который вызывает эту функцию каждые 500 миллисекунд.
Значения клэмпятся между 0 и 100, чтобы избежать выходов за пределы допустимого диапазона.
Обновление обработчиков событий:
При изменении значения слайдера или гироскопа обновляется baseRadiationLevel, а radiationLevel автоматически изменяется через функцию колебаний.
Это обеспечивает независимость основного уровня от отображаемых колебаний.
Обновление графика и звуковых сигналов:
updateDisplay теперь использует обновленный radiationLevel, который включает в себя колебания.
График автоматически обновляется с новыми данными, создавая эффект движущегося графика.
Звуковые сигналы (beeps) также зависят от radiationLevel, отражая колебания уровня радиации в реальном времени.
Результат:
После внесения этих изменений уровень радиации будет отображаться с небольшими случайными колебаниями, что сделает его отображение более реалистичным. График будет плавно двигаться, отображая эти изменения в реальном времени. Звуковые сигналы также будут соответствовать текущему отображаемому уровню радиации, обеспечивая полный реализм вашего Гейгера.
Дополнительные рекомендации:
Регулировка интенсивности колебаний:
При необходимости можно изменить диапазон delta в функции addRadiationFluctuation, чтобы увеличить или уменьшить интенсивность колебаний.
Плавность графика:
Увеличьте или уменьшите значение graphUpdateInterval для достижения желаемой плавности графика.
Оптимизация производительности:
Убедитесь, что частота обновления не слишком высокая, чтобы избежать избыточной нагрузки на браузер, особенно на мобильных устройствах.
Если у вас возникнут дополнительные вопросы или потребуется помощь с другими аспектами проекта, не стесняйтесь обращаться!