我正在使用画布在javascript中编写基于图块的游戏,并且想知道如何在鼠标输入图块的尺寸时创建一个简单的事件处理程序。
我过去曾经使用过jquery的http://api.jquery.com/mousemove/,但是对于一个非常简单的应用程序,但似乎无法解决我在这种情况下(快速)如何做到这一点。
嗯..
我开始写这篇文章而不知道怎么做,但我只是尝试使用像我上面开始的jquery mousemove。我有一个工作版本,但它看起来“慢”而且非常笨重。它似乎不够平滑或准确。
我将所有模式代码放入js小提琴中轻松分享: http://jsfiddle.net/Robodude/6bS6r/1/
所以发生的事情是:
1)jquery的mousemove事件处理程序触发
2)将鼠标对象信息发送到GameBoard
3)将鼠标对象信息发送到地图
4)遍历所有图块并向每个图块发送鼠标对象
5)然后,单个图块确定鼠标坐标是否在其边界内。 (并做了一些事情 - 在这种情况下,我只是将瓷砖属性更改为白色)
但这是我最关心的部分。
$("#canvas").mousemove(function (e) {
mouse.X = e.pageX;
mouse.Y = e.pageY;
game.MouseMove(mouse);
Draw();
});
function GameBoard() {
this.Map = new Map();
this.Units = new Units();
this.MouseMove = function (Mouse) {
this.Map.MouseMove(Mouse);
};
}
function Map() {
this.LevelData = Level_1(); // array
this.Level = [];
this.BuildLevel = function () {
var t = new Tile();
for (var i = 0; i < this.LevelData.length; i++) {
this.Level.push([]);
for (var a = 0; a < this.LevelData[i].length; a++) {
var terrain;
if (this.LevelData[i][a] == "w") {
terrain = new Water({ X: a * t.Width, Y: i * t.Height });
}
else if (this.LevelData[i][a] == "g") {
terrain = new Grass({ X: a * t.Width, Y: i * t.Height });
}
this.Level[i].push(terrain);
}
}
};
this.Draw = function () {
for (var i = 0; i < this.Level.length; i++) {
for (var a = 0; a < this.Level[i].length; a++) {
this.Level[i][a].Draw();
}
}
};
this.MouseMove = function (Mouse) {
for (var i = 0; i < this.Level.length; i++) {
for (var a = 0; a < this.Level[i].length; a++) {
this.Level[i][a].MouseMove(Mouse);
}
}
};
this.BuildLevel();
}
function Tile(obj) {
//defaults
var X = 0;
var Y = 0;
var Height = 40;
var Width = 40;
var Image = "Placeholder.png";
var Red = 0;
var Green = 0;
var Blue = 0;
var Opacity = 1;
// ...
this.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
};
this.MouseMove = function (Mouse) {
if ((Mouse.X >= this.X) && (Mouse.X <= this.Xmax) && (Mouse.Y >= this.Y) && (Mouse.Y <= this.Ymax)) {
this.Red = 255;
this.Green = 255;
this.Blue = 255;
}
};
}
答案 0 :(得分:4)
如果你有一个瓷砖网格,然后给定鼠标位置,你可以通过将X鼠标位置除以瓷砖的宽度来检索瓷砖的X和Y索引,将Y位置除以高度和地板两者。
这会使Map
成为MouseMove
:
this.MouseMove = function (Mouse) {
var t = new Tile();
var tileX = Math.floor(mouse.X / t.Width);
var tileY = Math.floor(mouse.Y / t.Height);
this.Level[tileY][tileX].MouseMove(Mouse);
};
编辑:您要求提供一些一般性建议。你走了:
Mouse
是一个简单的结构;我不认为它需要有自己的课程。也许使用对象文字。 (如{x: 1, y: 2}
)prototype
个对象,而不是对每个方法使用this.method = function() { ... }
。这可能会提高性能,因为它只需要创建一次函数,而不是每当创建该类的新对象时。