- Home /
Generating enemy that moves in Sine but want to randomize height?
I have one line of code that I've been stuck with on how to code it properly below:
currentPosition.y = Mathf.Sin(Time.time * 10f) * 100f + y;
where currentPosition
is a Vector2
type variable and y
is a float.
My game is a 2D sidescroller and I want my enemies (birds) to fly in a Sine motion but I want to change the height that they spawn at to Random height between -400f to 400f.
If it do a single fixed number like y = 100f
, the bird enemy flies in a straight direction with a Sine motion (up and down) but it is always being spawned at that fixed height (100f).
If I use Random.Range(-400f, 400)
the bird enemy will just erratically spaz between the top and bottom edges of the screen rapidly (400 max to -400 min).
How can I modify my code above so that it randomly generates the enemy along the y-axis between -400f and 400f without it spazzing out?
EDIT: to avoid confusion, I've renamed my y
float variable to "height"
Answer by NoseKills · Oct 17, 2017 at 06:24 AM
If your bird "erratically spazzes", I guess you must be calling Random.Range() in Update giving the bird a new base height every frame?
Pick a random y value in a method that gets called only once , like Start or Awake, and offset your bird in relation to that base height with the sine formula.
float y;
void Start(){
// Without the 'f' at the end of 400 you would be calling the integer version of Random.Range(), which only returns integer values
y = Random.Range(-400f, 400f);
}
void Update() {
currentPosition.y = Mathf.Sin(Time.time * 10f) * 100f + y;
}