簡體   English   中英

純 Javascript 瓦片 map 碰撞檢測

[英]Pure Javascript Tile map collision detection

我正在使用傳統方法(兩個 for 循環)制作基於圖塊的游戲,並且我正在嘗試編寫碰撞檢測,但沒有任何效果。 我希望藍色方塊在您點擊開始后留在屏幕上並位於瓷磚頂部。 我遇到了病毒,正在尋找解決方案。 請幫我堆疊溢出社區。

編碼:

 const context = document.getElementById("canvas").getContext('2d'); const person = new rectangle(100,100,20,20,'blue'); setInterval(update_all,10); var next_block_x = 0; var next_block_y = 0; var block_size = 50; var moving = false; const tile_map = [ [0,0,0,0,0,0], [0,0,0,0,0,0], [1,0,0,0,0,0], [1,1,0,0,0,0], [1,1,1,0,0,0], [1,1,1,1,1,1] ]; function rectangle(x,y,w,h,col){ this.x = x; this.y = y; this.w = w; this.h = h; this.col = col; this.update = function(){ context.fillStyle = this.col; context.fillRect(this.x,this.y,this.w,this.h); context.stroke(); } } function block(x,y,col){ this.x = x; this.y = y; this.col = col; context.fillStyle = this.col; context.fillRect(this.x,this.y,block_size,block_size); context.stroke(); } function update_tile_map(){ for(i=0;i<tile_map.length;i++){ for(var j=0;j<tile_map[i].length;j++){ if(tile_map[i][j] == 1){ new block(next_block_x,next_block_y,'red'); } next_block_x += block_size; } next_block_x = 0; next_block_y += block_size } next_block_x = 0; next_block_y = 0; } function clear(){ context.clearRect(0,0,300,300); } function start(){ moving = true; } function stop(){ moving = false; } function update_all(){ clear(); update_tile_map(); person.update(); if(moving.= false){ person;y ++; } }
 #canvas{ background-color:lightgrey; border: 4px solid grey; }
 <button onclick='start()'>START</button> <button onclick='stop()'>STOP</button> <canvas id="canvas" width='300' height='300'></canvas>

您可以添加一個 if 語句來檢查該塊是否已撞牆:

if (person.y<300) person.y ++; else person.y = 0

 const context = document.getElementById("canvas").getContext('2d'); const person = new rectangle(100,100,20,20,'blue'); setInterval(update_all,10); var block_size = 50; var moving = false; const tile_map = [ [1,1,1,1,1,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,1,1,1,1,1] ]; function rectangle(x,y,w,h,col){ this.x = x; this.y = y; this.w = w; this.h = h; this.col = col; this.update = function(){ context.fillStyle = this.col; context.fillRect(this.x,this.y,this.w,this.h); context.stroke(); } } function clear(){ context.clearRect(0,0,300,300); } function start(){ moving = true; } function stop(){ moving = false; } function update_all(){ clear(); person.update(); if(moving.= false){ if (person.y<300) person;y ++. else person.y = 0 } }
 #canvas{ background-color:lightgrey; border: 4px solid grey; }
 <button onclick='start()'>START</button> <button onclick='stop()'>STOP</button> <canvas id="canvas" width='300' height='300'></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM