In my 2D project I have a character launching a projectile at a target. I want the projectile to continue until it hits a target or leaves the ‘game space’ and I delete it. Here is my function for moving the projectile when it gets spawned:
private Vector2 targetPosition;
private Vector2 mouseLocation;
public float moveSpeed = 5;
void Start()
{
mouseLocation = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mouseLocation);
}
// Update is called once per frame
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
Currently the object stops when it reaches the targetPosition, but I want it to continue on it’s path indefinitely (until I destroy it later).
I’ve tried just scaling the targetPosition vector by multiplying it by 100f but I get rounding errors like so:
void Start()
{
mouseLocation = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mouseLocation);
Debug.Log("targetPosition: " + targetPosition.ToString("F3"));
targetPosition *= 100f;
Debug.Log("new targetPosition: " + targetPosition.ToString("F3"));
}
output:
targetPosition: (-3.485, -3.115)
new targetPosition: (-348.462, -311.539)
targetPosition: (3.254, -1.408)
new targetPosition: (325.385, -140.769)
targetPosition: (-0.469, 1.300)
new targetPosition: (-46.923, 130.000)
Am I approaching this wrong? Why is multiplying the vector giving rounding errors? Is there another way to get a vector that is a straight line between the spawn location and mouse location, but extended by a factor of 100?