I realise this is very similar to other 2D movement questions already posted but cant find a solution that fits the behaviour I'm looking for, so I'm posting in the hope that someone more knowledgeable than myself can give me a nudge in the right direction.
Here goes:
I have an object that I am moving round a canvas. This object always faces the cursor position and accelerates to a maximum speed when the mouse is held. now the issue I have is when implementing the movement of the object. I want the object to slowly loose velocity when no longer accelerating and to slowly change direction based on the acceleration and direction (imagine a boat going at top speed then hitting reverse instantly, I want it to slow to a stop before going in the other direction) so far I have logic along these lines in my code (simplified for ease of debugging, swapped in constant values instead of references):
velocityCalculation() {
//thrust
if (_thrust> 0) {
_velocity.x += mouseMagnitude.x * (_thrust * 0.1);
_velocity.y += -mouseMagnitude.y * (_thrust * 0.1);
}
if (_velocity.x != 0)
{
//drag
_velocity.x += -Math.sign(_velocity.x) * 2;
//cap velocity
if (_velocity.x > 100) _velocity.x = 100;
else if (_velocity.x < -100) _velocity.x = -100;
if (_velocity.x < 2 && _velocity.x > -2) _velocity.x = 0;
}
if (_velocity.y != 0) {
//drag
_velocity.y += -Math.sign(_velocity.y) * 2;
//cap velocity
if (_velocity.y > 100) _velocity.y = 100;
else if (_velocity.y < -100) _velocity.y = -100;
if (_velocity.y < 2 && _velocity.y > -2) _velocity.y = 0;
}
}
where mouseMagnitude is a normalised vector pointing towards the cursor, thrust is the current acceleration (probably named badly, I have no clue the correct terminology). Now if I place the cursor just off axis the object begins accelerating and moving normally however after reaching the correct direction of the mouse(shown as white arrow) it continues accelerating until its travelling diagonally (shown as red, objects velocity = 100x,100y) instead of in the direction of the mouse. I'm sure I'm missing something simple but how do I make the object continue travelling in the direction of the mouse instead of diagonally?