javascript - 相对于其父级位置重新定位 Sprite

标签 javascript rotation position sprite

这是一个与 HTML5/JavaScript 游戏开发相关的问题。 我需要旋转父 Sprite 并保持其子 Sprite 的位置和旋转正确对齐。 因此,如果父级旋转,子级应保持正确的位置和旋转。

谁知道这个公式是什么? enter image description here

最佳答案

您必须了解对象的本地坐标和世界坐标,这样您才能跟踪父子关系。如果你想做动画,这并不像看起来那么容易,但这里有一个例子。您要查找的“公式”位于 b.pos 中,用于计算相对于父对象的位置。

演示: http://jsbin.com/dahul/2/edit

// Some basic canvas utilities
// (see demo)

// Objects to be drawn on canvas
var a = {
  x: 0, // global coordinates
  y: 0, // ^
  vx: .1, // velocity
  vy: .1, // ^
  w: 100, // dimensions
  h: 100, // ^
  color: 'red'
};

var b = {
  parent: a, // relationship
  x: 0,
  y: 0,
  lx: .5, // local coordinates (percentage)
  ly: .5, // ^
  w: 25,
  h: 25,
  color: 'yellow',
  pos: function() { // calculate position relative to given parent
    return {
      x: this.parent.w * this.lx - this.w / 2,
      y: this.parent.h * this.ly - this.h / 2
    };
  }
};

// Draw boxes with parent-child relationship
// @param a {Object} Parent
// @param b {Object} Child
var draw = function(a, b, ctx, dt) {
  ctx.fillStyle = a.color;
  ctx.fillRect(a.x += a.vx * dt, a.y += a.vy * dt, a.w, a.h);
  ctx.fillStyle = b.color;
  ctx.fillRect(b.x + a.x + b.pos().x, b.y + a.y + b.pos().y, b.w, b.h);
};

// Initialize and animate canvas
document.body.appendChild(canvas(400, 400, function(ctx) {
  return render(function(dt) {
    ctx.clearRect(0, 0, 400, 400);
    draw(a, b, ctx, dt);
  });
}));

关于javascript - 相对于其父级位置重新定位 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748667/

相关文章:

android - ImageView 上的 TranslateAnimation (Android)

javascript - Div的定位

javascript - 如何仅将 onFocus 和 onBlur 事件应用于表单内的所有输入、选择框和文本区域

javascript - 数据表排序

c# - 将二维数组旋转 45 度

java - Sprite 旋转无法正常工作 LibGDX

css - 使用自动边距或 % 在父 div 中定位一个 div

javascript - 为什么 Underscore.js chain() 方法不是惰性的?

javascript - 动态添加选项

iphone - 设置自动旋转框架后,UIButtons 不响应触摸