import { defineComponent, h, reactive, toRefs, onMounted, onUnmounted, } from "@vue/runtime-core"; import Map from "../component/Map"; import Plane from "../component/Plane"; import Bullet from "../component/Bullet"; import EnemyPlane from "../component/EnemyPlane"; import { getGame } from "../Game"; import { hitTestTrctangle } from "../utils/index"; export default defineComponent({ setup(props, ctx) { const planeInfo = useCreatePlaneInfo(); // 子弹数据 const bullets = reactive([]); // 敌军数据 const enemyPlanes = reactive([ { x: 10, y: 10, width: 308, height: 207, }, ]); const handleAttack = (info) => { const createBulletInfo = () => { return { x: info.x + 100, y: info.y, }; }; bullets.push(createBulletInfo()); return; }; getGame().ticker.add(() => { // 让子弹动起来 // 改变子弹的y坐标 // const speed = 10; // bullets.forEach(bulletInfo => { // bulletInfo.y -= speed; // }) moveBullets(bullets); // 碰撞💥检测 enemyPlanes.forEach((enemyPlaneInfo) => { if (hitTestTrctangle(enemyPlaneInfo, planeInfo)) { ctx.emit("changePage", "endPage"); console.log("hit----"); } }); }); // 创建子弹 return { planeInfo, bullets, handleAttack, enemyPlanes, }; }, render(ctx) { // 渲染子弹 const renderBullets = () => { return ctx.bullets.map((info) => { return h(Bullet, { x: info.x, y: info.y }); }); }; // 渲染敌人飞机 const renderEnemyPlanes = () => { return ctx.enemyPlanes.map((info) => { return h(EnemyPlane, { x: info.x, y: info.y }); }); }; return h("Container", [ h(Map), h(Plane, { x: ctx.planeInfo.x, y: ctx.planeInfo.y, onAttack: ctx.handleAttack, }), ...renderBullets(), ...renderEnemyPlanes(), ]); }, }); const useCreatePlaneInfo = () => { const planeInfo = reactive({ x: 240, y: 680, width: 258, height: 364, }); // console.log(planeInfo) // 让飞机动起来 const { x, y } = useMovePlane(planeInfo.x, planeInfo.y); planeInfo.x = x; planeInfo.y = y; return planeInfo; }; const useMovePlane = (initX, initY) => { const speed = 20; const point = reactive({ x: initX, y: initY, }); const handleKeyDown = (e) => { switch (e.code) { case "ArrowUp": point.y -= speed; break; case "ArrowDown": point.y += speed; break; case "ArrowLeft": point.x -= speed; break; case "ArrowRight": point.x += speed; break; } }; onMounted(() => { window.addEventListener("keydown", handleKeyDown); }); onUnmounted(() => { window.removeEventListener("keydown", handleKeyDown); }); return toRefs(point); }; const moveBullets = (bullets) => { const speed = 10; bullets.forEach((bulletInfo) => { bulletInfo.y -= speed; }); };