在Unity游戏中以速度拖动不等于分辨率

cil*_*dr0 3 c# android touch screen-resolution unity-game-engine

我正在Unity中做一个游戏,它是一个太空射击游戏,我制作了一个用于移动我的宇宙飞船的脚本.这个游戏是为Android设备开发的,我正在用Touch移动这个游戏.这就像把船拖到你想要的位置.另外一个人必须注意,我不考虑你是否触摸船的中心以便拖动它.但是我有问题,根据我工作的设备,船没有正确跟踪拖拽,例如,如果我在平板电脑上,如果我用手指移动,让我们说3英寸,我的船只是移动一个.但是,在我的移动设备上,它工作正常.

我做错了什么?我附上了运动的代码:

void MovePlayer (Vector3 movement)
{
    GetComponent<Rigidbody> ().velocity = movement;
    GetComponent<Rigidbody> ().position = new Vector3 
        (Mathf.Clamp (GetComponent<Rigidbody> ().position.x, boundary.xMin, boundary.xMax), 
         0.0f, 
         Mathf.Clamp (GetComponent<Rigidbody> ().position.z, boundary.zMin, boundary.zMax));
    GetComponent<Rigidbody> ().rotation = Quaternion.Euler 
        (0.0f, 
         0.0f, 
         GetComponent<Rigidbody> ().velocity.x * -tilt);
}

void FixedUpdate ()
{
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {

        // Get movement of the finger since last frame
        Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;

        float moveHorizontal = touchDeltaPosition.x;
        float moveVertical = touchDeltaPosition.y;

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical) * speedMouse;
        MovePlayer (movement);
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢提前和最好的问候

rut*_*ter 7

触摸positiondeltaPosition以像素为单位,因此您无法假设结果在不同分辨率下保持一致.

根据您的设计需求,有几种方法可以缓解这种情况......

您可以将触摸表达deltaPosition为屏幕分辨率的一小部分:

float screenSize = Mathf.Max(Screen.width, Screen.height);
Vector2 touchDeltaPosition  = Input.GetTouch(0).deltaPosition;
Vector2 touchDeltaPercentage = touchDeltaPosition / screenSize;

//touchDeltaPercentage values will now range from 0 to 1
//you can use that as you see fit
Run Code Online (Sandbox Code Playgroud)

您可以使用主摄像头将屏幕坐标转换为世界位置,然后检查它们之间的差异:

Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

Vector3 screenCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 1f);
Vector3 screenTouch = screenCenter + new Vector3(touchDeltaPosition.x, touchDeltaPosition.y, 0f);

Vector3 worldCenterPosition = Camera.main.ScreenToWorldPoint(screenCenter);
Vector3 worldTouchPosition = Camera.main.ScreenToWorldPoint(screenTouch);

Vector3 worldDeltaPosition = worldTouchPosition - worldCenterPosition;

//worldDeltaPosition now expresses the touchDelta in world-space units
//you can use that as you see fit
Run Code Online (Sandbox Code Playgroud)

无论使用哪种方法,关键在于您需要一些与屏幕分辨率无关的单位.

与上述类似,您还可以使用主摄像头对地形,大型平面或场景中的其他一些对撞机进行光线投射.