Hey
I have a sprite which i want to decelerate but I am having trouble understanding how to do this correctly, i think i have over complicated it and got myself confused.
So i set my sprite path and speed like so:
obj.speed = 100; //km/hr
obj.velocity = distanceToWorld(obj.speed); // converts to game speed from real unit
var vectorX = obj.destX - obj.posX,
vectorY = obj.destY - obj.posY;
obj.normal = Math.sqrt(vectorX*vectorX + vectorY*vectorY);
obj.vectorX = vectorX / obj.normal;
obj.vectorY = vectorY / obj.normal;
obj.totalTime = obj.normal / obj.velocity; //time taken to complete path
Now once my sprite has reached the destX and destY (destination point). I want to slow the sprite down to its next destination point. But this is where I think I over complicated the method to do it.
My code looks like this for moving & slowing (using a boolean) the sprite down:
function slowSettings(obj,destX,destY){
obj.destX = destX;
obj.destY = destY;
var vectorX = obj.destX - obj.posX,
vectorY = obj.destY - obj.posY;
obj.normal = Math.sqrt(vectorX*vectorX + vectorY*vectorY);
obj.vectorX = vectorX / obj.normal;
obj.vectorY = vectorY / obj.normal;
var range = distanceToWorld(8) - obj.velocity; //8km/hr target speed for destination point converted to pixels
obj.brake = range / obj.normal;
}
function updatePosition(obj,brake){
var delta = new Date().getTime() - obj.timer;
if(brake){ //set to true if we want to slow the sprite down
obj.velocity += obj.brake*delta;
}
var distance = delta * obj.velocity;
obj.posX += (distance * obj.vectorX);
obj.posY += (distance * obj.vectorY);
obj.timer = new Date().getTime();
}
The current problem is the sprite slows down far before it reaches the destination. And I am not even sure if the way I am going about this is the cleanest way to do it?