I have a space craft in a 3d world that moves along the X Z plane. Given that I have 4 thrusters with one at each cardinal direction, and the ship can rotate itself about the y axis. Is it possible to find the correct combination of thrust vectors for the thrusters to equal a target velocity, given any possible rotation?
1 Answer
If your thrusters are aligned with the object's coordinate axes, then this is just a change of basis.
// Compute desired velocity change.
Vector2 deltaV = targetVelocity - rigidbody.velocity;
// Divide by time step to get acceleration to apply.
// ( If you're doing this in FixedUpdate,
// Time.deltaTime will automatically return fixedDeltaTime )
Vector2 acceleration = deltaV / Time.deltaTime;
// Convert to a thrust, respecting limits on max thruster output.
Vector2 thrust = Vector2.ClampMagnitude(acceleration/rigidbody.mass, maxThrust);
// Convert world-space vector into a local one, ignoring scaling.
Vector2 localThrust = transform.InverseTransformDirection(thrust);
// Fire thruster on the opposite side as the direction you want to move.
if (localThrust.x > 0) {
leftThruster.Fire(localThrust.x);
} else if (localThrust.x < 0) {
rightThruster.Fire(-localThrust.x);
}
if (localThrust.y > 0) {
rearThruster.Fire(localThrust.y);
} else if (localThrust.y < 0) {
frontThruster.Fire(-localThrust.y);
}
Here I've limited the thrust to the same maximum value in any direction, which should help make the controls more intuitive. But it does mean that when thrusting at a 45-degree angle, the two firing thrusters will be using only \$\frac 1 {\sqrt 2} \approx 70.7\%\$ of their maximum output. If they both fire at 100% power then you'd be able to accelerate faster on diagonals than directly ahead - which could be good for realism, or if you want to encourage diagonal maneuvers as a core skill/strategy, but might be distracting of confusing otherwise.
-
\$\begingroup\$ Wow i was really over thinking this. I totally forgot about the InverseTransformDirection function. Thanks for the solution. Works like a charm. \$\endgroup\$– JeremyOct 10, 2022 at 18:48