Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make a procedural jump in Unity C#?

I need to make a procedural jump in a board game in Unity C# (I conditionally have many points where the player has to jump from one to the other with different distances) which is called by the script. I cannot do animation because I need to calculate distance.

I’ve tried to use Vector3.Slerp which is much modified but it does not work like I imagined at all.

Here is modified Slerp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(There I’ve made another Vector3 because I need another axis in the jump)

Ideas ran out.

Please tell me how can I fix a problem in the script above or how I can do procedural jump else. Thank you so much.

>Solution :

Your index is always ever only to be 0. And the code you do in LateUpdate is fully redundant – simply assign the new position directly to transform.position.

I think what you are trying to achieve is to move your object smooth through the various positions provided by stand one by one.

So what you need is

  • store the current target point
  • move smooth towards it
  • when reaching the target point
    • previous target point becomes new start point
    • get next target point

and do this until you reach the very last one.

You could e.g. do this in a Coroutine like

public float moveSpeed;

public void StartMoveThroughWaypoints(IEnumerable<Vector3> waypoints)
{
    StartCoroutine(MoveThroughWaypoints(waypoints));
}

private IEnumerator MoveThroughWaypoints(IEnumerable<Vector3> waypoints)
{
    foreach(var waypoint in waypoints)
    {
        while(transform.position != waypoint)
        {
            transform.position = Vector3.MoveTowards(transform.position, waypoint, moveSpeed * Time.deltaTime);

            yield return null;
        }

        // as the "==" above has only a precision of 1e-5
        // ensure to end with a clean position
        transform.position = waypoint;

        // optional add delay to shortly hold on each waypoint
        //yield return new WaitForSeconds(1f);
        // or at least for one frame
        yield return null;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading