用可变比例变换中间点

时间:2016-06-10 21:05:17

标签: javascript math html5-canvas geometry

我有这段代码:

var Camera = function() {
  this.x;
  this.y;
  this.scale = 1.0;
  this.update = function(target, canvasWidth, canvasHeight, worldWidth, worldHeight) {
    this.scale = target.originalWidth / target.width;
    this.x = this.clamp(target.x - (canvasWidth / 2) * this.scale, 0, worldWidth - canvasWidth);
    this.y = this.clamp(target.y - (canvasHeight / 2) * this.scale, 0, worldHeight - canvasHeight);
  }
  this.clamp = function(value, min, max) {
    if (value < min) return min;
    else if (value > max) return max;
    return value;
  }
}

它的作用是让相机跟随目标。它工作得很好,但是如果比例改变,它就会偏离位置(更多地向上和向左到屏幕的中心)。

问题是,如何根据比例计算相机的x和y?

1 个答案:

答案 0 :(得分:0)

好的,通过实验我发现如果我这样做:

this.x = this.clamp(target.x * this.scale - (canvasWidth / 2), 0, worldWidth - canvasWidth);
this.y = this.clamp(target.y * this.scale - (canvasHeight / 2), 0, worldHeight - canvasHeight);

一切正常:)

相关问题