如何将模拟摇杆锁定在屏幕上? (3D)

时间:2019-03-31 15:33:59

标签: c# android unity3d 3d

https://imgur.com/a/cKTr9RJ

我正在创建一个脚本,用模拟摇杆移动摄像机(播放器),并且工作正常,但是这是一个3D项目,没有找到在2D透视图中附加模拟摇杆的方法。那就是操纵杆脚本,当您触摸屏幕时会显示它。

我应该让它跟着相机走,我该怎么做?还是仅仅是UI定位问题?

我尝试使用画布和UI,但似乎没有用,仍然在世界屏幕上随机显示,也许我做错了。

public Transform player;
public float speed = 5.0f;
private bool touchStart = false;
private Vector2 pointA;
private Vector2 pointB;


public Transform circle;
public Transform outerCircle;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
        circle.transform.position = pointA * -1;
        outerCircle.transform.position = pointA * -1;
        circle.GetComponent<SpriteRenderer>().enabled = true;
        outerCircle.GetComponent<SpriteRenderer>().enabled = true;
    }
    if (Input.GetMouseButton(0))
    {
        touchStart = true;
        pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    }
    else
    {
        touchStart = false;
    }
}
private void FixedUpdate()
{
    if (touchStart)
    {
        Vector2 offset = pointB - pointA;
        Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
        moveCharacter(direction * -1);
        circle.transform.position = new Vector2(pointA.x + direction.x, pointA.y + direction.y) * -1;
    }
    else
    {
        circle.GetComponent<SpriteRenderer>().enabled = false;
        outerCircle.GetComponent<SpriteRenderer>().enabled = false;
    }
}
void moveCharacter(Vector2 direction)
{
    player.Translate(direction * speed * Time.deltaTime);
}

}

每当触摸屏幕时,我想使其在屏幕限制(1920x1080)内显示2d。

0 个答案:

没有答案