首页 > 解决方案 > Unity - following finger only works for one direction

问题描述

I have made some code that should make my player move into the direction of the finger:

if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
    Vector2 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0));

    if (pos.x < rb.position.x)
    {
        movehorizontal = -1;
    }
    if(pos.x > rb.position.x)
    {
        movehorizontal = 1;
    }

    if (pos.y < rb.position.z)
    {
        movevertical = -1;
    }
    if(pos.y > rb.position.z)
    {
        movevertical = 1;
    }
}

Vector3 movement = new Vector3(movehorizontal, 0.00f, movevertical)*speed;

It's a 3D game, with a top-view, so my player starts at 0,0,0 and only moves along the x and z axis. My camera is positionated on 0,10,3. The following works on the x axis, so when my finger touches on the right side it goes to the right, if on the left to the left, but no matter where I touch it, it will only move to the front and not to the bottom of my screen.

I tried debugging, but the instructions werent working at the time.

标签: unity3d

解决方案


screentoWorldPoint 应存储为矢量3。此外,由于相机距离您的飞机 10 个单位,因此最后一个参数应为 10。

编辑,这只适用于直下的凸轮。无论相机角度如何,此代码都应该工作。

Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 1f));

Vector3 pointDelta = pos - Camera.main.transform.position;
float multiplier = -Camera.main.transform.position.y / pointDelta.y;
pos = Camera.main.transform.position + pointDelta * multiplier;

最后,这些行应该将 z 值相互比较

 if (pos.z < rb.position.z)

 if(pos.z > rb.position.z)

进行这些更改并让我们知道是否仍然存在任何其他问题


推荐阅读