- Home /
How to have a projectile move towards player's last position and go passed that position in the same direction?
Hey everyone, I have this code that shoots a projectile towards the player's last position, but once the projectile reaches that last position, it just stops in midair. Does anyone have any idea how to make the projectile go passed that last position in the same direction it was already traveling? Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Carrot : MonoBehaviour {
public float speed = 20f;
public float aimOffset = 1.0f;
private Transform player;
private Vector2 target;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
target = new Vector2(player.position.x, player.position.y + aimOffset); // position of player when carrot is spawned
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime); // move carrot towards player's last position
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
Destroy(gameObject);
}
}
private void OnBecameInvisible() // destroy carrots once they are off screen
{
Destroy(gameObject);
}
}
Answer by zombience · Mar 28, 2019 at 04:52 AM
The object stops moving because once it reaches the target the distance between the transform.position and the target is zero, so MoveTowards will move it a distance of zero.
What you should do instead is find the direction and continually add that to your transform's position, or translate your transform by that direction * speed.
something like this:
void Start()
{
Vector2 direction = target - transform.position;
}
void Update()
{
transform.position += direction * speed * Time.deltaTime;
}
While you're not wrong, I think it's better to use forward direction, that way projectiles travel appropriately.
Start()
{
transform.forward = (target.position - transform.position).normalized;
}
void Update()
{
transform.position = transform.position + transform.forward * speed * Time.deltaTime;
}