Need help moving towards players position on creation of bullet

Hello! Thank you for the help in advanced! Im new to unity so im struggling a bit.

Im trying to get a bullet to be created randomly and as soon as it spawns to move towards the players position right when it spawns, but it seems to be constantly moving towards the player without stopping until it hits the player.

I have been trying for hours to work my way around this and finding the coordinates of the player when it spawns, but even then it is failling.

public class MoveTowardsPlayer : MonoBehaviour
{
    [SerializeField] private GameObject bullet;
    public float speed = 5f * Time.deltaTime;
    public Transform player;
    private bool follow;
 

    // Start is called before the first frame update
    private void Start()
    {
   
   
    }

    // Update is called once per frame
    public void Update()
    {

        transform.position = Vector3.MoveTowards(transform.position, player.position, speed);

    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            //Debug.Log("Bullet Touching Ground");
            Object.Destroy(bullet);
        }
        if (collision.collider.tag == "Player")
        {
            Debug.Log("Touched Player");
            Object.Destroy(bullet);
        }
     
    }
 
 
 
}

I see your error, it’s quite simple to fix.

If you properly format your code, then I could tell you the line number it is on and suggest a potential fix.

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

You may edit your post above.

Okay, I believe I have fixed the formatting. My apologies, this is the first time ive posted here.

I believe you have!

See line 21 above?

That is responsible for continuously moving this object to the player.position

player.position is actually “live” and that’s why the bullet keeps steering.

What you want instead is:

  • observe the player in Start() method and record his position at that moment

  • move towards that stored position, not the “live” position in player.position

So something like a class variable:

private Vector3 storedPlayerPosition;

to store it, and use that variable instead of player.position in line 21 above.

Finally, inside of Start(), observe and record the player position.

// inside of Start()
// EDIT: this was wrong
storedPlayerPosition = player.position;

Does that make sense?

I understand what you mean. Although, it is unfortunately not working. They are still following the player in every step he takes rather than going to the saved position when the object was first created.

Also, if you wouldnt mind telling me how it would be possible to instead of going to the exact position, but instead straight towards it and even going passing? This way the bullet eventually touches the ground and I can then destroy the bullet. My apologies for the request of help.

That’s exactly what it should be doing if you did the three things I said above.

Repost your code now as it stands. Remember to use formatting.

This is the current code I have going on as of right now.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveTowardsPlayer : MonoBehaviour
{
    [SerializeField] private GameObject bullet;
    public Transform player;
    private bool follow;
    private Vector3 storePlayerPosition;

    // Start is called before the first frame update
    public void Start()
    {
        storePlayerPosition = transform.position;
       
    }

    // Update is called once per frame
    public void Update()
    {
            transform.position = Vector3.MoveTowards(transform.position, player.position, 1f * Time.deltaTime);
    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            //Debug.Log("Bullet Touching Ground");
            //Object.Destroy(bullet);
        }
        if (collision.collider.tag == "Player")
        {
            Debug.Log("Touched Player");
            //Object.Destroy(bullet);
        }
       
    }
}

As I suspected, you neglected to make this required change:

Line 22 above, what was originally Line 21

Forgive me, as I am totally new to all of this. I believe I made the appropriate changes, but it would appear the bullets remain in place once spawned.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveTowardsPlayer : MonoBehaviour
{
    [SerializeField] private GameObject bullet;
    public Transform player;
    private bool follow;
    private Vector3 storePlayer;

    // Start is called before the first frame update
    public void Start()
    {
        storePlayer = transform.position;
       
    }

    // Update is called once per frame
    public void Update()
    {
            transform.position = Vector3.MoveTowards(transform.position, storePlayer, 1f * Time.deltaTime);
    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            //Debug.Log("Bullet Touching Ground");
            //Object.Destroy(bullet);
        }
        if (collision.collider.tag == "Player")
        {
            Debug.Log("Touched Player");
            //Object.Destroy(bullet);
        }
       
    }
}

Line 15 is capturing the bullet’s position, not the player position.

Looking up at my post, I said the correct thing but I coded the wrong thing… my bad!

Change that line as I edited the post above.

Thank you! I made the fix and it seems to be working, half way unfortunately. It appears the bullet is not updating the player’s position if he were to move and another bullet would be summoned. I do appreciate the help. You have no idea how many hours I was looking to solve this issue.

Are you using some kind of object pooling?

Hey! Thank you for the assistance so far and sorry for the late reply. It’s unfortunately not working as intended. It seems that each bullet spawning is moving to a set point. Of (0, 1.9, 4.1) and im not sure why honestly. Each of them spawning is going to that set location and they’re not trying to head towards the player no matter where I put him. I am not sure whats going on if you could help please and thank you.

I am not using any code of Object Pooling in any of my other scripts.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveTowardsPlayer : MonoBehaviour
{
    [SerializeField] private GameObject bullet;
    public Transform player;
    private bool follow;
    private Vector3 storedPlayerPosition;

    // Start is called before the first frame update
    public void Start()
    {
        storedPlayerPosition = player.position;
    }

    // Update is called once per frame
    public void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, player.position, 5f * Time.deltaTime);
    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.tag == "Ground")
        {
            Debug.Log("Bullet Touching Ground");
            Object.Destroy(bullet);
        }
    }
}

Start printing stuff out, figure out why.

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

Thank you for the help. I will try using Debug.Log to see if the code is being executed or not.

I did fix the issue. Turns out putting the Prefab of “bullet” into the spawner inspector is what was causing the issue.