GML A free simple quadratic bezier curve script in GML

Discussion in 'Tutorials' started by andev, Feb 5, 2018.

  1. andev

    andev Member

    Joined:
    Jul 2, 2017
    Posts:
    444
    Put in 4 x/y coordinates and a lerp value to find the point. I couldn't find a script that did only this out the box in GML. Here's an example of implementation:
    [​IMG] [​IMG]

    GM Version: Any
    Target Platform: ALL
    Download: N/A
    Links: N/A

    The GML you're here for:
    Code:
    ///Bezier_Point_Find(lerp, p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y)
    /*
    Lerp is a value from 0-1 to find on the line between p0 and p3
    p1 and p2 are the control points
    
    returns array (x,y)
    */
    var t   = argument0;
    var p0x = argument1;
    var p0y = argument2;
    var p1x = argument3;
    var p1y = argument4;
    var p2x = argument5;
    var p2y = argument6;
    var p3x = argument7;
    var p3y = argument8;
    
    //Precalculated power math
    var tt  = t  * t;
    var ttt = tt * t;
    var u   = 1  - t; //Inverted
    var uu  = u  * u;
    var uuu = uu * u;
    
    //Calculate the point
    var px =     uuu * p0x; //first term
    var py =     uuu * p0y;
    px += 3 * uu * t * p1x; //second term
    py += 3 * uu * t * p1y;
    px += 3 * u * tt * p2x; //third term 
    py += 3 * u * tt * p2y;
    px +=        ttt * p3x; //fourth term
    py +=        ttt * p3y;
    
    //Pack into an array
    var PA; PA[0] = px; PA[1] = py;
    return PA;

    The original C#:
    It comes from a well written tutorial, which you can find here.
    GML doesn't define variable types, and also doesn't support vectors.
    Code:
    Vector3 CalculateBezierPoint(float t,
      Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3)
    {
      float u = 1 – t;
      float tt = t*t;
      float uu = u*u;
      float uuu = uu * u;
      float ttt = tt * t;
    
      Vector3 p = uuu * p0; //first term
      p += 3 * uu * t * p1; //second term
      p += 3 * u * tt * p2; //third term
      p += ttt * p3; //fourth term
    
      return p;
    }
     
    Woowoo, Alireza, tagwolf and 9 others like this.
  2. NeZvers

    NeZvers Member

    Joined:
    Mar 24, 2018
    Posts:
    320
    Up you go. More need to know this awesomeness!
     
    Lonewolff likes this.
  3. Lonewolff

    Lonewolff Member

    Joined:
    Jan 8, 2018
    Posts:
    1,150
    Agreed! I hadn't even seen this post before. Very nice!
     
    NeZvers likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice