Pretty new to Unity and i'm trying to make a very simple iphone game. , I'd like to know how to move a sprite (2D) move from random point A to random Point B not just that, but i want it to change direction halfway through.
here is my attempt:
public float speed;
public float minForce;
public float maxForce;
public float counter;
private float counter2;
void Start ()
{
Push ();
}
void Update ()
{
counter2 -= Time.deltaTime;
if ( counter2 < 0)
{
Push ();
counter2 = counter;
}
}
void Push ()
{
float force = Random.Range(minForce, maxForce);
float x = Random.Range(-1f, 1f);
float y = Random.Range(-1f, 1f);
rigidbody2D.AddForce( force * new Vector2(x, y) * speed);
}
}
I'm not quit satisfied with using force, also tried Vector2.lerp but for some reason it just teleported instead of smoothing. Also i want to make it randomly change position only once.
here is my perp attempt:
private Vector2 startPoint ;
public float speed ;
public float counter;
private float counter2;
void Start ()
{
startPoint = transform.position;
}
// Update is called once per frame
void Update ()
{
counter2 -= Time.deltaTime;
if ( counter2 < 0)
{
RandomPosition ();
counter2 = counter;
}
}
void RandomPosition ()
{
float counter = speed * Time.deltaTime;
float x = Random.Range(-50f, 50f);
float y = Random.Range(-100f, 100f);
Vector2 endPoint = new Vector2(x, y);
transform.position = Vector2.Lerp(transform.position, endPoint, Time.deltaTime * speed);
}
}