What I’m trying to achieve is having my player perform a sideways dash, as a dodge maneuver. This is the best I’ve gotten scrambled together (scouring the internet), but I think I’ve misunderstood the use of lerp or something. The character does move, but it just performs an instant teleportation.
In addition the character moves to the left, and a bit diagonally downwards, even though in unity I’ve only set the target position to -10, 0, 0?
public class Dodge4 : MonoBehaviour
{
public Vector3 targetPosition;
public float smoothFactor = 10;
void Update()
{
if (Input.GetButtonDown("Jump Left"))
{
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smoothFactor);
}
}
}
While my previous answer that I gave at 1am was incorrect, I still believe that updating the start vector of lerp while lerping is a bad idea since it makes the lerp theoretically infinite. Probably use some other kind of smoothing such as a sinusoidal curve?
public class Test : MonoBehaviour
{
private Vector2 startPos; // position from where the player is dashing
private Vector2 targetPos; // position to where the player is dashing
public Vector2 dashDistance; // dash distance. Set x to -10, y to 0
private bool isDashing = false;
private float timeSinceDash;
public float dashTime; // time of dash (in seconds)
private float dashInterpolationCounter;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isDashing == false) // prevents dashing during the dash. Set KeyCode.Space to desired button press
{
startPos = transform.position; // sets the start position of the dash to the player position
targetPos += dashDistance;
isDashing = true;
timeSinceDash = 0;
dashInterpolationCounter = 0;
}
if (timeSinceDash < dashTime) // if the time since start of dash is < the time of dash (ie. dash is unfinished)
{
timeSinceDash += Time.deltaTime;
dashInterpolationCounter = Mathf.Sin(Mathf.PI/2 * timeSinceDash / dashTime); // change it so that it is one at the end of the dash
}
else // the time since start of dash = the time of dash (ie. dash is finished)
{
isDashing = false;
}
if (isDashing == true)
{
transform.position = Vector2.Lerp(startPos, targetPos, dashInterpolationCounter);
}
}
}