- Home /
Physics based click to move
Background: physics based top down, 2.5D space shooter (something like multiplayer Unitroids)
We have a physics based manual contol working well (fwd/back, stop, strafe, and turn)
We have left click to move to a place/orientation using the physics we developed in manual control, but we are having trouble scripting ship control to do it intelligently (overshoot, slowing down too soon, very inefficient paths, etc). It doesn't have to be a Unity script, just seeing a good algorithm would be very helpful.
Answer by Barsonax · Sep 04, 2016 at 04:00 PM
I made a method for this. Just be sure that all variables use the same time step (rigidbody.velocity for instance is in seconds while you apply your forces every fixed update which is 50 times per second).
I know this is a old question but iam sure you are not the only one wanting to do this.
/// <summary>
/// Tries to minimize the error. Useful when working with physics and trying to arrive at a position and similar problems.
/// A example of such a problem would be a car that has to move to a goal and has to arrive exactly at that goal without overshooting.
/// </summary>
/// <param name="error"></param>The error. This is a value that indicates how much we are off our goal. Think of this as the distance to your goal
/// <param name="deltaStep"></param>How much the error will change in the next step. Think of this as the current speed of your car.
/// <param name="maxDeltaDelta"></param>The max amount of change that we can apply to deltaStep. Think of this as the acceleration of your car.
/// <returns></returns>
public static float CalculateArrival(float error, float deltaStep, float maxDeltaDelta)
{
double goalDeltaStep;
var minInfluenceRange = deltaStep - maxDeltaDelta;
var maxInfluenceRange = deltaStep + maxDeltaDelta;
if(error > minInfluenceRange && error < maxInfluenceRange)
{
goalDeltaStep = -error; //This prevents overstepping
}
else
{
if (error >= 0)
{
goalDeltaStep = -Math.Sqrt(Math.Abs(2f * maxDeltaDelta * error));
}
else
{
goalDeltaStep = Math.Sqrt(Math.Abs(2f * maxDeltaDelta * error));
}
}
var difference = goalDeltaStep - deltaStep;
return Mathf.Clamp((float)difference, -maxDeltaDelta, maxDeltaDelta);
}
Your answer
Follow this Question
Related Questions
Click to move a character in a terrain 1 Answer
Keep Horizontal Momentum after Jump 2 Answers
RigidBody2D Movement Stuttering 3 Answers
Why are these object passing through each other? 1 Answer
Non slippery movement 1 Answer