- Home /
Why isn't my 2d object facing the way it is moving?
I am having an issue of getting my 2D object to point towards where it is going. To start with, I have a script that has my 2D object (an arrow) traveling from its location to a random spot. The arrows move as directed and once it gets to the random spot, it then picks a new random spot and moves to it, etc. However, every time it moves, it does not turn and face the direction it is going.
Here is my randomization code:
using UnityEngine;
public class RandomizeArrows : MonoBehaviour
{
public float minX;
public float minY;
public float maxX;
public float maxY;
public float speed;
Vector2 targetPosition;
// Start is called before the first frame update
void Start()
{
targetPosition = GetRandomPosition();
}
// Update is called once per frame
void Update()
{
if ((Vector2)transform.position != targetPosition)
{
transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
else
{
targetPosition = GetRandomPosition();
}
}
Vector2 GetRandomPosition()
{
float randomX = Random.Range(minX, maxX);
float randomY = Random.Range(minY, maxY);
return new Vector2(randomX, randomY);
}
}
I have tried several quaternions to make the arrows face the direction without luck!
Should I be using Quanternion.RotateTowards or Quanternion.LookRotation? I have tried several of these and failed miserably. It isn't even worth putting the code in as I know I don't know what to put where in the variables.
Any help would be much appreciated! Thanks in advance!