将播放器移到精确的触摸/鼠标单击位置 [英] Move player to exact touch/mouse click location

查看:110
本文介绍了将播放器移到精确的触摸/鼠标单击位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的2D统一游戏中,我试图将精灵移动到触摸/光标的位置(现在是单击鼠标).

In my 2D unity game, I am trying to move my sprite to the location of my touch/cursor (right now it's a mouse click).

我的子画面位于(173,48,-52.1). 但是,当我单击可能距离几个像素的位置时,我的位置更改为(399,129,0),并且我的精灵显然投掷到了未知的地方.

My sprite is at the location (173, 48, -52.1). However, when I click a location that is probably a few pixels away my position is changed to (399, 129, 0) and my sprite is apparently hurled into the vast unknown.

if (Input.GetMouseButtonDown(0))
{

    //fingerPos =  Input.GetTouch(0).position;
    fingerPos = Input.mousePosition;
    transform.position = fingerPos;
    Debug.Log(transform.position);
}

编辑

当前代码

if (Input.GetMouseButtonDown (0)) {
        fingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Desktop
        transform.position = fingerPos;
        Debug.Log (transform.position);
    }   

更新.显然,当我单击记录的位置(以及精灵移动到的位置)时,直接在相机上.参考图片

Update . Apprantly, when I click the position that is recorded (and the one the sprite is moved to) is directly ON the camera. Refer to image

推荐答案

transform.position在世界坐标中. Input.mousePosition返回像素坐标中的值.您需要将其转换为世界坐标.

transform.position is in world coordinates. Input.mousePosition returns values in pixel coordinates. You need to convert this into world coordinates.

fingerPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); //Mobile
fingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Desktop

然后您可以将其分配给您的位置.

Then you can assign it to your position.

transform.position = fingerPos;

编辑:

if (Input.GetMouseButtonDown(0))
{
    fingerPos = Input.mousePosition;
    fingerPos.z = 10;
    fingerPos = Camera.main.ScreenToWorldPoint(fingerPos);

    transform.position = fingerPos;
    Debug.Log(transform.position);
}

这篇关于将播放器移到精确的触摸/鼠标单击位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆