I have created an object that has a constant velocity going right across the screen, however, when it comes into contact with a wall, I want it to face the direction its moving, not the direction of its velocity. My inital thought was to create two variables position, and positionOld, my thought is that if you can get the direction of movement from the new frames position and the last frames position.
public class TurtleController : MonoBehaviour
{
private Rigidbody2D rb;
public float speed;
public Vector2 velocity;
public bool manual;
private Vector2 position;
private Vector2 positionOld;
// Start is called before the first frame update
void Start()
{
rb = GetComponent();
positionOld = Vector2.zero;
}
// Update is called once per frame
void Update()
{
position = rb.position;
Vector2 moveinput = new Vector2(Input.GetAxis("Horizontal")*speed, Input.GetAxis("Vertical")*speed);
if (manual)
rb.velocity = moveinput;
else
rb.velocity = velocity;
float angle = Mathf.Atan2((position.y-positionOld.y), (position.x - positionOld.x)) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
positionOld = position;