简体   繁体   中英

How to follow mouse position

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 OnMouseMove(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

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 az 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 OnMouseMove(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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM