Advertisement

Applying 2d transformations effecting camera scroll and positions of sprites

Started by January 13, 2016 07:30 AM
-1 comments, last by CelticSir 8 years, 11 months ago

Hello

I have an annoying problem that I cannot seem to work out how to solve.

I have a simple drawing of a circle and a square. The circle is transformed by both it's shape and its position. The square is not transformed but it's position is to keep it in the relatively correct place in game world.

The problem how ever, when i move my camera, the movement is not correct. It seems to exponentially move the more I click and drag. Additionally my square does not move correctly relative to the rest of the sprites.

I'm sure i've made a math logic error some where but I do not know where.

This is my draw function:

Javascript:


function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.save();

/// offsets
  var o = {};          
      o.x = canvas.centerX - (camera.x*camera.scale);
      o.y = canvas.centerY - (camera.y*camera.scale);
////////////
  ctx.setTransform(1, 0, 0, 1, o.x,o.y);
  ctx.beginPath();

// note: camera.transform = {'x':1,'y':0.7};
  var position = positionMath(square,camera.transform);
  ctx.rect(position.x - 5, position.y - 5, 10, 10);      
  ctx.fill();

  ctx.restore();
  ctx.save();

  ctx.beginPath();
  // note: camera.transform = {'x':1,'y':0.7};
  ctx.setTransform(camera.transform.x, 0, 0, 
                   camera.transform.y,o.x,o.y);

  var origin = positionMath(circle,{'x':1,'y':1});

  ctx.arc(origin.x, origin.y, circle.radius, 0, Math.PI * 2);
  ctx.stroke();

  ctx.restore();

  window.requestAnimationFrame(draw);

}

Granted this probably won't help detect the problem so I made an online example of the bugs occurring here: https://jsfiddle.net/batbbz13/

Notice when you click and drag the circle and square do not move together correctly, and notice also when clicking and dragging the movement of camera is not 1 to 1 with the mouse movement, it increases speed for some odd reason.

You can edit the code and update then run to see the changes. I have been trying all evening to work out the problem but its not working.

I hope some one knows a lot about 2D transformations and can explain where my logic is failing me, its giving me a huge headache trying to solve it.

This topic is closed to new replies.

Advertisement