Для создания программы на Vue 3 с использованием Composition API и Pinia, которая визуализирует плавный 3D-график симуляции полёта от Земли до Меркурия по кратчайшему пути (дуге большого круга), мы можем использовать следующие популярные библиотеки:
- Three.js — для создания 3D-графики.
- Pinia — для управления состоянием приложения.
- GSAP (GreenSock Animation Platform) — для анимации полёта.
Вот пример реализации:
Установка зависимостей
Сначала установите необходимые зависимости:
npm install three @vue/composition-api pinia gsap
Код приложения
1. main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
2. stores/simulationStore.js (Pinia Store)
import { defineStore } from 'pinia';
export const useSimulationStore = defineStore('simulation', {
state: () => ({
earthPosition: { x: 0, y: 0, z: 0 }, // Позиция Земли
mercuryPosition: { x: 50, y: 0, z: 0 }, // Позиция Меркурия
spacecraftPosition: { x: 0, y: 0, z: 0 }, // Текущая позиция корабля
isFlying: false, // Флаг, указывающий, идет ли полет
}),
actions: {
startFlight() {
this.isFlying = true;
},
updateSpacecraftPosition(position) {
this.spacecraftPosition = position;
},
resetFlight() {
this.isFlying = false;
this.spacecraftPosition = { x: 0, y: 0, z: 0 };
},
},
});
3. components/ThreeDScene.vue
<template>
<div ref="sceneContainer" class="scene-container"></div>
</template>
<script setup>
import * as THREE from 'three';
import { onMounted, ref, watch } from 'vue';
import { useSimulationStore } from '../stores/simulationStore';
import gsap from 'gsap';
const sceneContainer = ref(null);
const simulationStore = useSimulationStore();
let scene, camera, renderer, spacecraft;
onMounted(() => {
initScene();
animate();
});
function initScene() {
// Создаем сцену
scene = new THREE.Scene();
// Создаем камеру
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 100;
// Создаем рендерер
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
sceneContainer.value.appendChild(renderer.domElement);
// Добавляем Землю
const earthGeometry = new THREE.SphereGeometry(2, 32, 32);
const earthMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
const earth = new THREE.Mesh(earthGeometry, earthMaterial);
earth.position.set(simulationStore.earthPosition.x, simulationStore.earthPosition.y, simulationStore.earthPosition.z);
scene.add(earth);
// Добавляем Меркурий
const mercuryGeometry = new THREE.SphereGeometry(1, 32, 32);
const mercuryMaterial = new THREE.MeshBasicMaterial({ color: 0xffa500 });
const mercury = new THREE.Mesh(mercuryGeometry, mercuryMaterial);
mercury.position.set(simulationStore.mercuryPosition.x, simulationStore.mercuryPosition.y, simulationStore.mercuryPosition.z);
scene.add(mercury);
// Добавляем космический корабль
const spacecraftGeometry = new THREE.BoxGeometry(1, 1, 1);
const spacecraftMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
spacecraft = new THREE.Mesh(spacecraftGeometry, spacecraftMaterial);
spacecraft.position.set(simulationStore.spacecraftPosition.x, simulationStore.spacecraftPosition.y, simulationStore.spacecraftPosition.z);
scene.add(spacecraft);
// Наблюдаем за изменением позиции корабля
watch(
() => simulationStore.spacecraftPosition,
(newPosition) => {
spacecraft.position.set(newPosition.x, newPosition.y, newPosition.z);
},
{ deep: true }
);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
// Анимация полета
watch(
() => simulationStore.isFlying,
(isFlying) => {
if (isFlying) {
gsap.to(simulationStore.spacecraftPosition, {
duration: 5,
x: simulationStore.mercuryPosition.x,
y: simulationStore.mercuryPosition.y,
z: simulationStore.mercuryPosition.z,
ease: 'power1.inOut',
onUpdate: () => {
simulationStore.updateSpacecraftPosition(simulationStore.spacecraftPosition);
},
onComplete: () => {
simulationStore.resetFlight();
},
});
}
}
);
</script>
<style scoped>
.scene-container {
width: 100%;
height: 100vh;
}
</style>
4. App.vue
<template>
<div>
<button @click="startFlight" :disabled="simulationStore.isFlying">
{{ simulationStore.isFlying ? 'В полете...' : 'Начать полет' }}
</button>
<ThreeDScene />
</div>
</template>
<script setup>
import { useSimulationStore } from './stores/simulationStore';
import ThreeDScene from './components/ThreeDScene.vue';
const simulationStore = useSimulationStore();
function startFlight() {
simulationStore.startFlight();
}
</script>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
button {
position: absolute;
top: 20px;
left: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
z-index: 10;
}
</style>
Как это работает:
- Pinia Store управляет состоянием полёта и позицией космического корабля.
- Three.js создает 3D-сцену с Землёй, Меркурием и космическим кораблём.
- При нажатии на кнопку запускается анимация полёта с использованием GSAP, которая обновляет позицию корабля в реальном времени.
- Полёт происходит по прямой линии между Землёй и Меркурием.
Результат:
Пользователь видит 3D-сцену с Землёй и Меркурием. При нажатии на кнопку "Начать полет" корабль плавно перемещается от Земли к Меркурию.
Ответ: Программа успешно визуализирует полёт от Земли до Меркурия с использованием Vue 3, Composition API, Pinia и Three.js.