Hi, ScreenToWorldPoint takes a Vector3 which is the x and y of the mouse, and z for the depth you wish to observe. When you pass it Input.mousePosition, that gives it a vector that looks like Vector3(x, y, 0). Since the third value is 0, it looks at your mouse’s position and interprets its x, y world coordinates at z = 0.
What you want to do is use the x and y component from Input.mousePosition, but set the depth yourself to the z-plane that your user is observing at the time. Here’s some code that works, I used passed it the camera’s far clipping plane so with this example you’ll see the world coordinates at the maximum view distance of the camera, they will definitely be more than 0 and 1 that you observed. Change the farClipPlane to the depth of your objects or scene, and it should work as needed for your application. If you don’t want to attach the camera to this, just comment out the camera.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseTracker : MonoBehaviour
{
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 screen_mouse_pos = Input.mousePosition;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(screen_mouse_pos.x, screen_mouse_pos.y, cam.farClipPlane));
//Debug.Log(Input.mousePosition);
Debug.Log("Mouse: " + mousePos);
}
}
Since the title of your question asks how to make the player shoot projectiles towards that position, here’s an expanded version of the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float game_z = 8;
public GameObject bullet;
public float velocity = 30f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 screen_mouse_pos = Input.mousePosition;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(screen_mouse_pos.x, screen_mouse_pos.y, game_z));
if (Input.GetButtonDown("Fire1"))
{
GameObject fired_bullet = Instantiate(bullet, transform.position, Quaternion.identity);
Vector3 bullet_direction = new Vector3(mousePos.x, mousePos.y, game_z) - transform.position;
fired_bullet.GetComponent<Rigidbody>().velocity += velocity * bullet_direction;
}
}
}
I’m using a bullet gameobject projectile with a Rigidbody attached to it. You can change it to a Rigidbody2D and just modify the code to use a Vector2 bullet_direction, but this will work in 2D and 3D. If you didn’t want to use a rigidbody, you’ll have to have a script attached to your bullet, access it using GetComponent(), and tell it the direction and velocity to go at. Then in that ScriptName script, add some code under Update() that changes the position of the transform over time at the velocity you want to use.