这几天尝试一下写一个能实现联机的网页小游戏,想学习使用一下tcp,udp啥的协议,先把简单框架搭起来吧,明天完善一下然后研究一下咋通信,然后先尝试一下用websoket入门
基本框架如下,但还没做完。。
RectangleMove.vue
1 <template> 2 <div class="CanvasContainer"> 3 <canvas width="1000" height="800" ref="backgroundCanvas"></canvas> 4 </div> 5 </template> 6 7 <script setup> 8 import { onMounted, ref } from "vue" 9 10 const backgroundCanvas = ref(null) 11 let ctx = null 12 //玩家集合 13 const players = [] 14 //子弹集合 15 const bullets = [] 16 //按键字典 17 const keys = { 18 w: false, 19 a: false, 20 s: false, 21 d: false 22 } 23 //按下按键 24 function keyDown(e) { 25 if (keys.hasOwnProperty(e.key)) { 26 keys[e.key] = true 27 } 28 } 29 //松开按键 30 function keyUp(e) { 31 if (keys.hasOwnProperty(e.key)) { 32 keys[e.key] = false 33 } 34 } 35 //画 36 function draw() { 37 //清空画布 38 ctx.clearRect(0, 0, backgroundCanvas.value.width, backgroundCanvas.value.height) 39 40 players.forEach(player => { 41 player.draw() 42 }) 43 } 44 //更新位置 45 function updatedPosition() { 46 //自己移动 47 players.forEach((player) => { 48 if (player.me) { 49 if (keys.w) player.y -= player.ySpeed 50 if (keys.s) player.y += player.ySpeed 51 if (keys.a) player.x -= player.xSpeed 52 if (keys.d) player.x += player.xSpeed 53 } 54 }) 55 } 56 //动画 57 function animate() { 58 updatedPosition() 59 draw() 60 requestAnimationFrame(animate) 61 } 62 //初始化 63 onMounted(() => { 64 const canvas = backgroundCanvas.value 65 ctx = canvas.getContext("2d") 66 67 const player1 = new Player(100, 100, 60, 60, "red", 2, 2, true) 68 players.push(player1) 69 //绑定按键事件 70 window.addEventListener('keydown', keyDown) 71 window.addEventListener('keyup', keyUp) 72 //启动 73 animate() 74 }) 75 //玩家类 76 class Player { 77 constructor(x, y, width, height, color, xSpeed, ySpeed, me) { 78 this.x = x 79 this.y = y 80 this.width = width 81 this.height = height 82 this.color = color 83 this.xSpeed = xSpeed 84 this.ySpeed = ySpeed 85 this.me = me 86 } 87 88 draw() { 89 ctx.fillStyle = this.color 90 ctx.fillRect(this.x, this.y, this.width, this.height) 91 } 92 93 } 94 95 class Bullet { 96 constructor(x, y, width, height, color, xSpeed, ySpeed, from) { 97 this.x = x 98 this.y = y 99 this.width = width 100 this.height = height 101 this.color = color 102 this.xSpeed = xSpeed 103 this.ySpeed = ySpeed 104 this.from = from 105 } 106 } 107 </script> 108 109 <style scoped> 110 .CanvasContainer { 111 display: flex; 112 width: 100vw; 113 height: 100vh; 114 background-color: #000; 115 align-items: center; 116 justify-content: center; 117 } 118 119 canvas { 120 background-color: #000333; 121 border: red solid 2px; 122 } 123 </style>
