Drawing an X shape on a HTML5 canvas and checking for collisions with a border(在 HTML5 画布上绘制 X 形状并检查与边框的冲突)
问题描述
我正在开发一个 HTML 5 迷宫游戏.
I am working on a maze game in HTML 5.
这是我用来在画布上绘制X"的函数(使用触摸板,用户将通过迷宫导航 X).
Here is the function which I use to draw an "X" on the canvas (using the touchpad, the user will navigate the X through the labyrinth).
dim = 8;
function rect(x,y,xdim){
ctx.beginPath();
ctx.moveTo(x - xdim, y - xdim);
ctx.lineTo(x + xdim, y + xdim);
ctx.moveTo(x + xdim, y - xdim);
ctx.lineTo(x - xdim, y + xdim);
ctx.strokeStyle = '#FF5000';
ctx.stroke();
}
问题出在checkcollision函数上,主要是这段代码:
The problem is in the checkcollision function, mainly in this piece of code:
ctx.getImageData(checkx, checky, 16, 16);
我正在寻找一种最佳方式来检查画布上X"占用的所有空间.
我使用的代码中有更多注释.
There are more comments in the code i used.
问题:1. 有时,X 有点超出边界2. 有时,X 没有靠近,在它和边框之间留出几个像素.
Issues: 1. Sometimes, the X goes a little passed the border 2. Sometimes, the X doesn't get close, letting a few pixels between it and the border.
function checkcollision(checkx, checky){
var collision = 0;
/*
User presses an arrow key
Calculate where that would move the square to.
Look at all of the pixels on the maze image that the square will cover
in its new position (our square is 15x15 so we look at 225 pixels)
Are any of the pixels black (the maze is white with black borders.
If a pixel is black that means the square would collide with a border)
YES: then do not move
NO: then move
*/
var imgd = ctx.getImageData(checkx, checky, 15, 15);
pix = imgd.data;
for (var i = 0; n = pix.length, i < n; i += 4){
if (pix[i] == 0) {
collision = 1;
} else if(pix[i] == 255 && pix[i + 1] == 0){
winner = "yes";
}
}
return collision;
}
我相信 getImageData 会得到一个矩形,该矩形从角落的 x,y 位置开始.
I believe the getImageData gets a rectangle which starts from the x,y position in a corner.
所以也许有一种方法可以使用 checkx 和 checky 作为中心的坐标来绘制它并检索一个 16 像素宽的正方形
So maybe there is a way to draw it using the checkx and checky as the coordinates for the center and retrieve a square 16 pixels wide
推荐答案
哇,问题写的很清楚了:
Wow, writing the question made it clear:
var imgd = ctx.getImageData(checkx - xdim, checky - xdim, 16, 16);
小伙伴们
这篇关于在 HTML5 画布上绘制 X 形状并检查与边框的冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 HTML5 画布上绘制 X 形状并检查与边框的冲突
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01