- Home /
Translate to a target goal position and facing direction and stop
Hi There,
I have a 2d, top down navel game I've been working on and am having trouble with pathing the ship to a target position.
I have the speed set, it adds increments of acceleration and deceleration and can move to a target point and stop right now (so long as its moving in a straight line). I'm sure its a solvable problem as I know both the velocity, the changes in velocity, and the rotation speed ( which is currently fixed and being slerped). The translate is applied as a forward linear translate relative to the ship (no lateral or reverse movement) I have two problems tripping me up now.
When we start not facing the target, the arc of the movement means I overshoot to goal and end up rotating endlessly around the goal. This is the main problem. This occurs when the beginning direction does not point a the goal, I basically just need to calculate an arc from one point & direction to a target point and direction. I've been thinking its basically calculating a bezier curve maybe, I'm just not really sure how to approach it.
Ideally I'd like to adjust the trajectory so that I reach the target goal facing the target direction as well, but I'd settle for just reaching the target, stopping and then rotating in place. Mostly its problem #1 that concerns me. Even if someone can point me in the right direction, I was thinking either using a bezier curve to create the path from end goal to current position.
Alternatively, if anyone can suggest a 2d pathfinding kit on the asset store that could do this, that would be great. I'm using Nav2d right now which is great but it moves laterally causing the ship to drift and turn in strange ways.
The current speed is set directly from the acceleration and deceleration values, which are constant, and the rotation is a constant slerp. Any help or insight into this would be greatly helpful, thanks!
// get direction to target
Vector3 vectorToTarget = targetPosition - transform.position;
angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotateSpeed);
// move to target
if( distanceToTarget > stoppingDistance ){
// calculate current speed with acceleration
currentSpeed = currentSpeed + (acceleration * Time.deltaTime);
currentSpeed = Mathf.Min ( currentSpeed, maxMovementSpeed);
}else{
// decelerate
currentSpeed = currentSpeed - (deceleration * Time.deltaTime);
currentSpeed = Mathf.Max (currentSpeed, 0f);
}
Your answer
Follow this Question
Related Questions
Child GameObject can't use MovePosition on parent's Rigidbody2D? 3 Answers
Is there a standardized way for creating a 2D ball physics movement method? 0 Answers
Need help with my movement script.. :( 1 Answer
Moving a non-player object in a random direction which bounces off other objects. 2 Answers