我使用圆形html div元素作为行星,使用一个小div元素作为球(这是一个迷你高尔夫游戏)。我的代码如下:
function Ball([x, y, r]) {
this.b = document.createElement("DIV");
this.b.className = "ball";
this.b.style.width = r * 2 + "px";
this.b.style.height = r * 2 + "px";
this.b.style.left = x + "px";
this.b.style.top = y + "px";
this.start = [x, y];
this.v = [0, 0];
this.planets = levels.list[levels.currLevel][1];
// the above line just has the information for each planet
document.body.appendChild(this.b);
}
Ball.prototype.physics = function () {
var b = this;
var a = [0.25, -0.09];
this.planets.forEach(function (info) {
// change acceleration from each planet
});
b.v[0] += a[0];
b.v[1] += a[1];
b.b.style.left = (parseFloat(b.b.style.left) + b.v[0]) + "px";
b.b.style.top = (parseFloat(b.b.style.top) + b.v[1]) + "px";
setTimeout(function () {b.physics();}, 30);
}
主要问题似乎是我每秒用JavaScript访问CSS属性33次。
我是一个相当新的程序员,所以如果有一个完全替代的方法来制作形状和移动它们而不处理DOM元素和CSS,我真的很想知道!