我已经在Unity中创建了一个Android游戏。长宽比为9:16。屏幕左下方有一个多维数据集,我正在尝试编写代码,以便如果单击屏幕,则该多维数据集将移至屏幕的底部中间,然后再次单击至右下角。
我在线搜索,但没有发现任何有用的信息。有人可以帮我一个忙或为我提供教程吗?
答案 0 :(得分:1)
void Update()
{
if (Input.touchCount > 0)
{
// Someone clicked the screen!
}
}
您可能需要在这些数字上加上一些偏移,因为它将是边缘的确切像素:
Vector3 worldBottomMiddle = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width / 2, 0f));
Vector3 worldBottomRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0f));
transform.position = Vector3.MoveTowards(position);
Vector3 worldBottomMiddle;
Vector3 worldBottomRight;
Vector3 target;
bool cubeIsMoving = false;
void Start()
{
worldBottomMiddle = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width / 2, 0f));
worldBottomRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0f));
target = transform.position;
}
void Update()
{
if (Input.touchCount > 0)
{
cubeShouldMove = true;
if (target == worldBottomMiddle)
target = worldBottomRight;
else
target = worldBottomMiddle;
}
if (cubeShouldMove & Vector3.Distance(transform.position, target) < 1)
{
transform.position = Vector3.MoveTowards(target);
}
}
类似的事情应该起作用,但是那并不漂亮。如果您想更详细地了解事情的进展,我可以将解决方案编辑为更漂亮的解决方案。
编辑:刚刚看到还有另一个答案;您应该使用该代码在各个职位之间循环。
答案 1 :(得分:0)
您可以使用Camera.ScreenToWorldPoint在屏幕坐标和世界坐标之间进行转换。
float distanceFromCamera = 1.0f;
Vector3 bottomCenter = new Vector3(Screen.Width/2, 0, distanceFromCamera);
Vector3 worldPos = Camera.main.ScreenToWorldPoint(bottomCenter);
myCube.transform.position = worldPos;
您可以将屏幕相对位置存储在数组中,并在它们之间循环:
Vector3[] positions = new Vector3[] {
new Vector3(Screen.Width/2f, 0f, 1f),
new Vector3(Screen.Width, 0f, 1f)
};
int counter = 0;
void Update() {
if (Input.GetMouseDown(0)) {
Vector3 pos = positions[Mathf.Min(positions.Length-1, counter++)];
Vector3 worldPos = Camera.main.ScreenToWorldPoint(pos);
myCube.transform.position = worldPos;
}
}