[SOLVED] Fire Projectile towards last position of player and make it continue in that direction

Hi guys. OK, i managed to make a script that makes an enemy shoot a projectile at last player position. The projectile will hit the player if he is standing still but will miss if he moves, giving him a chance. However, the projectile stops at the target position and stay there.

My problem is how to make the projectile move towards last player position and continue moving in that direction indefinitely?

I want to avoid using rigidBody if possible because the projectile gets stuck in objects and causes weird interaction with the other enemies.

    void Start()
    {
       // Get last know player position, y is +1 so the bullet appears to "float above ground a bit"
       lastPos = new Vector3(player.transform.position.x, player.transform.position.y+1,          player.transform.position.z);[/INDENT]
    }

    // Update is called once per frame
    void Update()
    {
       // Move the projectile towards player's last position
     transform.position = Vector3.MoveTowards(transform.position, lastPos, speed * Time.deltaTime);

    }

Thanks in advance.

1 Like

Vector3.MoveTowards moves the bullet towards the player’s last knwon position, what you want is to move it in the player’s last known direction. This should work:

    void Start()
    {
        // Add + 1 to player's last known position so bullet appears to float above ground.
        Vector3 playerPos = new Vector3(player.position.x, player.position.y + 1, player.position.z);

        // Aim bullet in player's direction.
        transform.rotation = Quaternion.LookRotation(playerPos);
    }

    // Update is called once per frame
    void Update()
    {
        // Move the projectile forward towards the player's last known direction;
        transform.position += transform.forward * speed * Time.deltaTime;
    }
9 Likes

Thanks Isaiah =). Glad to receive a reply, especially when starting out in Unity and seeking advice in these forums.

I am using navmesh for my enemies to move towards my player so they are already facing the playing and line 14 works perfectly.

I will keep the Quaternion.LookRotation in mind in case I need to objects to “aim” at the player first.

Cheers =D

Glad it helped you. :slight_smile:

The simplest method is actually Transform.LookAt:

transform.LookAt(player.position);

However, Quaternion.LookRotation is helpful when you want to look at a Vector3 instead of a Transform. Which I needed in the above example since I was modifying the player’s position beforehand and returning a vector3 to look at instead of the transform.

Also for simple questions like this Unity Answers might be a better place. They probably have answers to very similar questions there already and you can learn a lot by just browsing it.

Best of luck with Unity!

1 Like

this was super helpful

Once again old posts have saved me.

Great to see people are still finding this helpful. You can also just hit that like button to show your appreciation, instead of resurrecting an ancient thread :wink:

4 Likes

I am also having the same problem, but in 2d. I already have a fireball script that can fire straight on and hit a wall based on Rigidbody.AddForce, but I cannot make it follow the player using the same principles. Any ideas?
Also, here is my fireball script:

using UnityEngine;

public class Fireball :MonoBehaviour
{
    public GameObject shooter;
    private float _xDir;
    private Rigidbody2D _rb;
    private bool _hasCollided;
    public bool followPlayer;
    private const float RotateSpeed = 5f;
    private const float MoveSpeed = 5f;
    private const float FollowTimer = 0.005f;
    public float followTimerCountdown = FollowTimer;
    private PlayerController player;
   

    private void Start()
    {
        _xDir = shooter.transform.localScale.x;
        transform.localScale = new Vector3(_xDir/Mathf.Abs(_xDir), 1, 1);
        _rb = GetComponent<Rigidbody2D>();
        player = FindObjectOfType<PlayerController>();
    }


    private void OnTriggerEnter2D(Collider2D other)
    {
       
        if (shooter.CompareTag("Player"))
            // if the shooter of this fireball is the player, then set the collisions to:
            _hasCollided = other.CompareTag("DestroyAble") || other.CompareTag("Ground");
        else if (shooter.CompareTag("DestroyAble"))
            // otherwise, if the shooter of this fireball is any enemy or cannon, then set the collisions to:
            _hasCollided = other.CompareTag("Player") || other.CompareTag("Ground");
       
       
       
    }

    private void Update()
    {
        if (!_hasCollided)
        {
            if (followPlayer)
            {
                //The area that I want to have the script for the fireball to follow the player
               
            }
            else
            {

                _rb.AddForce(new Vector2(5 * _xDir / Mathf.Abs(_xDir), 0));
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

@aristheviking looks like you want a vector instead of quaternion. You can convert a quaternion using the eulerAngles but it will probably be easier to just do this:

if (followPlayer)
{
    // Get player direction and normalize it so it doesn't exceed 1.
    Vector3 aim = (playerObject.transform.position - transform.position).normalized;
    // Add force based on that direction, modifying it as needed.
    _rb.AddForce(aim * speed);
}
1 Like

Wow thanks a lot, Isaiah!
The only problem is, I have the Cannon shooting two fireballs at a time, and they are following the exact same ai. is there a way to make it wiggle a bit and move around objects?
I tried Random.Range, but that just made its landing destination different.

That’s a lot more complicated and the exact way to do this completely depends on what effect you want. But it sounds like you just want them to be offset a bit so they don’t follow the same exact path?

Where are you using Random.Range? Using that in fixed update to apply a little random force continuously should work very well for fireballs and offset them each a little. You could also make them homing missiles (good tutorial here) and fire each one at a different angle so they each follow a slightly different path.

Here is a link to a video to show you what I mean:

@IsaiahKelly I think I got it working with A* Pathfinding

@aristheviking Sorry for not responding sooner. Got busy and totally missed your posts :sweat_smile:. Thanks for making that video. It’s very helpful.

The rotation issue you see is caused from the fireball’s forward facing direction not matching the rigid body’s, which is transform.up in the example script. To fix this all you need to do is either rotate the sprite in a paint program so forward direction is up, or change all occurrences of transform.up to transform.down/right/left so it matches the sprite’s facing direction.

To make the fireball not follow the player at first, set angleChangingSpeed to something very low at start and then increase value after some time. Here’s a script I made based on the original HomingMissile example that uses an AnimationCurve to smoothly increase turn speed over time.

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class HomingMissile : MonoBehaviour
{
    [Tooltip("Transform to home in on")]
    public Transform target;
    [Tooltip("Constant forward movement speed")]
    public float moveSpeed = 5;
    [Tooltip("How quickly missile will rotate towards target")]
    public float turnSpeed = 50;
    [Tooltip("Amount of turn speed applied over time")]
    public AnimationCurve turnSpeedCurve;
    [Tooltip("Total time (in seconds) to apply curve")]
    public float turnSpeedCurveTime = 1;

    Rigidbody2D body;
    float curveTime = 0;

    private void Start()
    {
        // Automatically get rigidbody component so we don't have to manually.
        body = GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        Vector2 direction = (Vector2)target.position - body.position;
        direction.Normalize();
        curveTime += Time.fixedDeltaTime / turnSpeedCurveTime;
        float rotateSpeed = turnSpeed * turnSpeedCurve.Evaluate(curveTime);
        float rotateAmount = Vector3.Cross(direction, transform.right).z;

        body.angularVelocity = -rotateSpeed * rotateAmount;
        body.velocity = transform.right * moveSpeed;
    }
}

That or Unity’s NavMesh is something you’ll definitely want to use if you want them to navigate around obstacles.

I am having a bit of an issue and it appears you have the solution. I am trying to get a projectile to fire straight and not follow the nose cone of the aircraft. For example if I fire at a target and move my craft the “bullet” will no longer be heading in the same direction, but will move in whichever direction I am. If you could provide a basic generic code to solve this problem It would be appreciated.

1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 public class firebolts : MonoBehaviour {
6 public GameObject projectile;
7 public float projectilespeed;
8
9
10
11
12// Update is called once per frame
13 void Update ()
14 {
15 if (Input.GetKeyDown (KeyCode.Space))
16 {
17 GameObject plasmabolt = Instantiate (projectile,transform) as GameObject;
18 Rigidbody rb = plasmabolt.GetComponent();
19 rb.velocity = (transform.rotation * -40);
20
21 }
22 }
23}