Search Unity

Better smooth random location

Discussion in 'Scripting' started by Kethis, Feb 18, 2010.

  1. Kethis

    Kethis

    Joined:
    Sep 10, 2009
    Posts:
    28
    In the procedural content examples available on the main website there is an example of a cube take a smooth random walk within a certain area using Perlin noise. I tried to get this example to work on a different project, but kept getting errors so I decided to just redo it.

    Code (csharp):
    1. // BrownianMotion.js
    2. var impulseScalar : float = 1;
    3. var moveRadius : float = 5;
    4. var anchor : GameObject = null;
    5.  
    6. private var tooFarAway : boolean = false;
    7. private var impulseAwayFromAnchor : boolean = false;
    8. private var impulseVector : Vector3 = Vector3.zero;
    9.  
    10. function FixedUpdate () {
    11.     impulseVector = Vector3(Random.value,Random.value,Random.value);
    12.     impulseVector -= Vector3(0.5,0.5,0.5);
    13.     impulseVector *= impulseScalar;
    14.    
    15.     tooFarAway = moveRadius < Vector3.Distance(anchor.transform.position , transform.position);
    16.     impulseAwayFromAnchor = 0 > Vector3.Dot(impulseVector, anchor.transform.position - transform.position);
    17.     if ( impulseAwayFromAnchor  tooFarAway )
    18.         impulseVector *= -1;
    19.     rigidbody.AddForce(impulseVector*Time.deltaTime, ForceMode.Impulse);
    20. }
    This implementation simulates Brownian motion (wiki article : http://en.wikipedia.org/wiki/Brownian_motion ; useful visualization : http://galileoandeinstein.physics.virginia.edu/more_stuff/Applets/brownian/brownian.html ).

    It tries to keep the attached object within a certain range of an anchoring object (or a position vector, with a tiny tweak). When it exceeds this range, it will only have force applied on it that points towards (within 90 degrees of) the anchor.

    The above example code works fairly well on a rigidbody of mass about 0.1 or 0.2.

    I have noticed that if you leave it running for a long period of time it can build up energy, bouncing off of the edges of its bounding area, and end up oscillating. If this becomes a problem you can give the rigidbody some drag.
     
  2. gabrielstuff

    gabrielstuff

    Joined:
    Aug 14, 2013
    Posts:
    15
    This works nicely. Good job.