How do I get bullet to move towards mouse when spawned.

I’m attempting to have a bullet spawn at the players position when the mouse is clicked and move towards the mouse cursors position at spawn. however each time the bullet spawns it will only move up and to the right. I noticed that if I move the player not only will the bullet speed up or slow down depending on the direction I move but the bullet will also change the direction that it moves as well. I cannot for hte life of me figure out how to get this working.

Any help would greatly be appreciated.

Here is my code for the player to spawn the bullet.

if (Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log(“mouse clicked”);

        player_bullet = (GameObject)Instantiate(player_bullet, transform.position, Quaternion.identity);
    }

And here is the code I use in the bullet to move towards the camera.

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

public class player_bullet : MonoBehaviour
{
public float bulletspd = 10f;

public Rigidbody2D bullet;

Vector3 moveposition;

void Start()
{
    Debug.Log("bullet spawned");
    bullet = GetComponent<Rigidbody2D>();

    moveposition = (Camera.main.ScreenToWorldPoint(Input.mousePosition));
    moveposition.z = 0;
    moveposition.Normalize();

    float step = bulletspd * Time.deltaTime;

    bullet.velocity = Vector3.MoveTowards(transform.position, moveposition, step);
}

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

}

So line 10…
You are setting moveposition to the camera’s position, but then 0’ing out the z axis?
Is this what you want? I dont think it is but i just wanted to check…

I think you want to fire a ray from the camera, using the mouse.Inputposition…

Also you probably want to work out the direction, normalize it… then move the bullet using Force as opposed to directly editing the bullets transform…

Regardless i don’t know why you’re using ‘MoveTowards’ to set the velocity…

All your movement logic is in the Start method which is only called once. You need to move it to Update so it is called every frame;

using UnityEngine;

public class player_bullet : MonoBehaviour
{
    public float Bulletspeed = 10f;
    public Rigidbody2D Bullet;

    private Vector3 _moveposition;

    void Start()
    {
        Debug.Log("bullet spawned");
        Bullet = GetComponent<Rigidbody2D>();

        _moveposition = (Camera.main.ScreenToWorldPoint(Input.mousePosition));
        _moveposition.z = 0;
        _moveposition.Normalize();
    }

    private void Update()
    {
        var step = Bulletspeed * Time.deltaTime;
        Bullet.velocity = Vector3.MoveTowards(transform.position, _moveposition, step);
    }
}