简体   繁体   中英

Reposition a sprite relative to its parents position

This is an HTML5/JavaScript game development related question. I need to rotate a parent sprite and keep its child sprite's position and rotation correctly aligned. So if the parent rotates, the child should maintain the correct position and rotation.

Does anyone know what the formula for this is? 在此处输入图片说明

You have to know about the object's local and world coordinates, so you can keep track of the parent-child relationship. It is not as easy as it seems if you want to do animation, but here's an example. The "formula" you're looking for is in b.pos , to calculate to position relative to the parent object.

Demo: 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);
  });
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM