ScreeToWorldPoint issue

Good afternoon!

I am currently trying to make a 3d game, where there is a sword which should move with the mouse on the x- and y-axis. I tried with this code:

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

public class movement : MonoBehaviour
{
   
    void Start()
    {
       
    }

   
    void Update()
    {
        Vector3 mouse_position = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        transform.position = new Vector3(mouse_position.x,mouse_position.y,transform.position.z);
    }
}

But because of some reason, when I run the program the sword moves a little bit then stays there.
I would appreciate any help!

By passing Input.mousePosition directly into the raycaster, you are leaving the z component of that Vector3 object as zero.

This means “cast into the scene zero distance from the camera,” so the calculated world position is right up in your face.

Assign Input.mousePosition to a temporary Vector3, then set the z coordinate to how far into the scene you want the world position to be. Every mouse position maps to an infinite number of world positions going out on a long ray from the camera eye through the mouse point, so you need to say “I want the point that is 10 units away” for instance.

Thank you for the quick reply! So this should work! 6 is the distance of the sword from the camera. But when I start it the sword just jump back into, where z = 6 is and it’s still not moving

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

public class movement : MonoBehaviour
{
   
    void Start()
    {
       
    }

   
    void Update()
    {
        Vector3 mouse_position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y,6);

        transform.position = mouse_position;