Hi, I’ve got a game where a 2d sprite randomly moves around the screen, this is done like this:
using UnityEngine;
using System.Collections;
public class RandomMove: MonoBehaviour {
public float MinForce = 20f;
public float MaxForce = 40f;
public float DirectionChangeInterval = 1f;
private float directionChangeInterval;
public new Rigidbody2D rigidbody2D;
void Awake() {
rigidbody2D = GetComponent<Rigidbody2D>();
}
// Use this for initialization
void Start () {
directionChangeInterval = DirectionChangeInterval;
push();
}
// FixedUpdate is called after a set time interval
void FixedUpdate () {
directionChangeInterval -= Time.deltaTime;
if (directionChangeInterval < 0) {
push();
directionChangeInterval = DirectionChangeInterval;
}
}
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));
}
}
I’d like to setup push so that it will also change the object to face the direction it’s moving (the Z rotation), but I haven’t had any luck. I’ve been googling and trying things but, nothing so far. I need a way to get the Z value that would leave it facing the new direction.