游戏效果图
通过鼠标拖拽在画布上添加墙壁,通过方向键控制多边形上下左右移动,遇到墙壁则无法前进。
需要解决的问题
鼠标按下,鼠标拖动,鼠标释放事件的检测
多边形的绘制
墙壁的绘制
多边形和墙壁的碰撞检测(实质上是圆和线段的相交判断)
MYCode:
<html>
<head>
<title>迷宫</title>
<script>
var canvas_width = 900;
var canvas_height = 350;
var ctx;
var canvas;
var everything = [];
var cur_wall;
var wall_width;
var wall_style = “rgb(200,0,200)”;
var walls = [];
var in_motion = false;
var unit = 10;
function Token(sx, sy, rad, style_string, n)
{
this.sx = sx;
this.sy = sy;
this.rad = rad;
this.draw = draw_token;
this.n = n;
this.angle = (2 * Math.PI) / n;
this.move = move_token;
this.fill_style = style_string;
}
function draw_token()//绘制正n边形
{
ctx.fill_style = this.fill_style;
ctx.beginPath();
var i;
var rad = this.rad;
ctx.moveTo(this.sx + rad * Math.cos(-0.5 * this.angle), this.sy + rad * Math.sin(-0.5 * this.angle));
for (i = 1; i < this.n; i++)
ctx.lineTo(this.sx + rad * Math.cos((i – 0.5) * this.angle), this.sy + rad * Math.sin((i – 0.5) * this.angle));
ctx.fill();
}
function move_token(dx, dy)
{
this.sx += dx;
this.sy += dy;
var i;
var wall;
for (i = 0; i < walls.length; i++)
{
wall = walls[i];
if (intersect(wall.sx, wall.sy, wall.fx, wall.fy, this.sx, this.sy, this.rad))
{
this.sx -= dx;
this.sy -= dy;
break;
}
}
}
function Wall(sx, sy, fx, fy, width, styleString)
{
this.sx = sx;
this.sy = sy;
this.fx = fx;
this.fy = fy;
this.width = width;
this.draw = draw_line;
this.strokeStyle = styleString;
}
function draw_line()
{
ctx.lineWidth = this.width;
ctx.strokeStye = this.strokeStyle;
ctx.beginPath();
ctx.moveTo(this.sx, this.sy);
ctx.lineTo(this.fx, this.fy);
ctx.stroke();
}
//note
var mypent = new Token(100, 100, 20, “rgb(0,0,250)”, 5);
everything.push(mypent);
function init()
{
canvas = document.getElementById(“canvas”);
ctx = canvas.getContext(‘2d’);
//note
canvas.addEventListener(‘mousedown’, start_wall, false);
canvas.addEventListener(‘mousemove’, stretch_wall, false);
canvas.addEventListener(‘mouseup’, finish_wall, false);
window.addEventListener(‘keydown’, getkey_and_move, false);









