Hello I have a question we can follow mouse position 2d game like this in new Input System
void Update()
{
transform.position = position;
}
public void onm ouseMove(InputAction.CallbackContext context)
{
if(playerHealth.health>0)
{
position= Camera.main.ScreenToWorldPoint(context.ReadValue<Vector2>());
}
}
Its Work fine Ortoghraphic Camera, but When i convert the Perspective Camera doesnt work I need that perspective Camera... So how can i do that
CodePudding user response:
Below is an edited version of this previous answer I wrote.
As mentioned in the comment above, note that ScreenToWorldPoint
needs also a Z
component
A screen space position (often mouse x, y), plus a z position for depth (for example, a camera clipping plane).
indicating how far from the given Camera
the point should be projected into the world.
In order to overcome this you can use a mathematical Plane
so you can get a point projected next to the object using ScreenPointToRay
in a Plane.Raycast
(which is a mathematical raycast, has nothing to do with physics or collision detection)
// In general store the camera reference as Camera.main is very expensive!
[SerializeField] Camera camera;
void Start()
{
camera = Camera.main;
// ...
}
public void onm ouseMove(InputAction.CallbackContext context)
{
if(playerHealth.health > 0)
{
var plane = new Plane(camera.transform.forward, transform.position);
var ray = camera.ScreenPointToRay(context.ReadValue<Vector2>());
plane.Raycast(ray, out var hitDistance);
position = ray.GetPoint(hitDistance);
}
}