Public Group

# Easing a camera offset

This topic is 1181 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,

I am trying to get my camera to move with an easing movement to a position i click on my game out canvas. It currently seems to shoot off at light speed, and always in the same direction no matter where I click on my screen.

I tried to calculate the direction based on where i clicked relative to the middle of my screen. I am using JavaScript by the way, and this was my attempt:

self.easing = function(x) {
return 0.5 + 0.5 * Math.sin((x - 0.5) * Math.PI);
}

self.mouseEvents = function(e,el){
var mousePos = mouse.relativePosition(e,el); //relative to element that was clicked {'x':int,'y':int} format
var parent   = el;
if(e.button == 0){ //left click
//middle of element is our camera position for user
var initial   = {'x':canvas.width/2,'y':canvas.height/2},
delta     = {'x':mousePos.x - initial.x,  'y':mousePos.y - initial.y},
timeStart = new Date().getTime();
timeLength= 800;

function update(){
function fraction(t){
canvas.offsetX -= initial.x + t * delta.x,
canvas.offsetY -= initial.y + t * delta.y;
}
var t = (new Date().getTime() - timeStart) / timeLength;
if (t > 1) {
fraction(1);
clearInterval(parent.scroll);
} else {
fraction(self.easing(t));
}
}
parent.scroll = setInterval(update, 10);
}

// called from main game loop (infinite loop):

self.draw = function(){
var x = img.x - (img.width/2) - canvas.offsetX;
var y = img.y - (img.height/2) - canvas.offsetY;
canvas.ctx.drawImage(img,x,y);
}



I also made a fiddle of the code: http://jsfiddle.net/p61f5k3z/

I am curious where I have gone wrong? I am currently thinking its my math logic some where, but I can't figure out what the mistake is.

Edited by thefollower

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633725
• Total Posts
3013558
×