【发布时间】:2012-03-18 20:24:55
【问题描述】:
我有一个递归函数可以在画布上移动一些圆圈。被覆盖的圆圈被放大(放大)并且所有其他圆圈被推开。 推动的圆圈推动其他圆圈,依此类推,直到缩放完成。
我收到一个错误“超出最大调用堆栈大小”,我理解这个问题,但我只是不知道如何解决它...... 我找到了解决递归问题的三种可能的解决方案:
- 将递归改为迭代
- 使用memoization
- 使用设置超时
但我认为我不能使用它们:
- 由于需要的操作数未知,我无法实现迭代
- 我不太了解 memoization,但我认为它也不适合(或者我错了,有人可能会以不同的方式告诉我?)
- 我不能使用 SetTimeout,因为它应该在这个特定的动画中阻塞函数调用。
我该如何解决这个问题?
// Pushes circles aside when some other circle leans on these circles (on zoom in)
var moveCirclesAside = function(circle1, circleToSkip, groupOfMoves) {
var count = circles.length;
for (var i = 0; i < count; i++) {
// Skip the same circle
if (i == circle1.i) {
continue;
}
// Also skip the circle which was intended not to move any further
if (circleToSkip != null && i == circleToSkip.i) {
continue;
}
// Get second circle
var circle2 = circles[i];
// Calculate a distance between two circles
var dx = circle2.x - circle1.x;
var dy = circle2.y - circle1.y;
var distance = Math.sqrt((dx * dx) + (dy * dy));
// If circles already collided need to do some moving...
if (distance <= circle1.r + circle2.r + OD.config.circleSpacing) {
// Get collision angles
var angle = Math.atan2(dy, dx);
var sine = Math.sin(angle);
var cosine = Math.cos(angle);
// Some circle position calculation
var x = OD.config.circleSpacing;
var xb = x + (circle1.r + circle2.r);
var yb = dy * cosine - dx * sine;
// Save each state (move) of any circle to the stack for later rollback of the movement
groupOfMoves.push(copyCircleByVal(circle2));
// Move the circle
circle2.x = circle1.x + (xb * cosine - yb * sine);
circle2.y = circle1.y + (yb * cosine + xb * sine);
// Make sure that circle won't go anywhere out of the canvas
adjustCircleByBoundary(circle2);
// If moved circle leans against some other circles make sure that they are moved accordingly
// And such related moves must be grouped for correct rolback of moves later - so we pass 'groupOfMoves' var
moveCirclesAside(circle2, circle1, groupOfMoves);
}
}
};
【问题讨论】:
标签: javascript recursion