- Home /
Constantly updating a targets position in relation to a projectile.
Hello!
I'm trying to figure out how to to make a projectile keep moving once it hits the target position, but the target is no longer there.
So I have my player and an enemy projectile. I'm using this code on the prefab of the projectile:
private Transform player;
private Vector2 target;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
target = new Vector2(player.position.x, player.position.y);
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
The code works great, however when the player moves out of way, the projectile just sits at the position the player was at. I'm looking for the projectile to keep on it's path if it does not hit the player, even though it has hit the player's old position.
Any help with this will be MUCH appreciated! Thanks!
Answer by tonialatalo · Aug 29, 2020 at 09:42 PM
Get a direction vector from the start to the target position
Set it's length to match the speed, so that's your movement vector
Apply that in the update, so it'll just continue straight on and not care about the player position
In code:
private Vector3 motion;
void Start()
{
Vector3 sourceToDestination = player.position - transform.position;
motion = sourceToDestination.normalized * speed;
}
void Update()
{
transform.position += motion * Time.deltaTime;
}