Search Unity

Pendulum Problem

Discussion in 'Scripting' started by Dzxyan, Mar 26, 2014.

  1. Dzxyan

    Dzxyan

    Joined:
    Sep 23, 2013
    Posts:
    167
    I got a script to show how the pendulum works,

    Code (csharp):
    1.  
    2.  
    3. public enum Path
    4.     {
    5.         XY, Normal
    6.     }
    7.  
    8.     public Path path;
    9.     public float speed;
    10.     public float height;
    11.     public int freq;
    12.  
    13. void Start()
    14.     {
    15.         startPosition = transform.position;
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.  
    22.         if (transform.position.x < startPosition.x || transform.position.x > startPosition.x + distance)
    23.         {
    24.             speed *= -1;
    25.         }
    26.  
    27.  
    28.         float x = transform.position.x + speed * Time.deltaTime;
    29.  
    30.         switch ((int)path)
    31.         {
    32.  
    33.             case 0:
    34.                 transform.position = new Vector3(x, startPosition.y + SinPathFunc(x - startPosition.x), transform.position.z);
    35.                 break;
    36.             case 1:
    37.                 transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z );
    38.                 break;
    39.         }
    40.     }
    41.  
    42.     float SinPathFunc(float x)
    43.     {
    44.  
    45.         float y;
    46.         y = height * Mathf.Sin((x * Mathf.PI) / (distance / freq));
    47.         return y;
    48.  
    49.     }
    50.  
    but i got a problem,
    the pendulum is work like this

    $1.jpg

    that a bit not suitable for me
    because i wanna make it like this,

    $2.jpg

    so any help?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    you're only effecting it triginometrically in the y direction, you need to in the x direction as well.

    Your x will mostly likely be the Cosine of the angle (this will have a 0 value start you at the top), and your y will be Sine.

    You'll have a center point, and you'll add the Cos(x) * radius to the x of the center, and you'll add Sin(y) * radius to the y center.
     
  3. Dzxyan

    Dzxyan

    Joined:
    Sep 23, 2013
    Posts:
    167
    can have the answer more details?