英文:
How to control an object with a finger in Unity3D?
问题
我是新手程序员。我正在为智能手机编写一个简单的游戏(我认为很多人知道它叫做“乒乓球”)。这是一个供两人玩的游戏。我需要将屏幕分成两个区域。每个人都应该能够用手指沿x轴控制对象。因此,对象只会沿x轴改变位置。
我能够自己编写这个脚本:
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) * new Vector2(1, 0);
Vector2 mousePosition2 = mousePosition + new Vector2(1, -4.74f);
transformPosition1.transform.position = mousePosition2;
这个脚本根据鼠标的x轴位置来改变对象的位置。但我不知道如何限制它的区域并将其分为两个玩家。提前感谢您的帮助。对不起,我的英语不太好。请在回答中不要使用复杂的语言结构。
英文:
I'm new to programming. I am writing a simple game (I think many people know it under the name "Ping Pong") for smartphones. A game for two people. I need the screen to be divided into two areas. Everyone within their area should be able to control the object with their finger along the x axis. Accordingly, the object changes its position only along the x axis.
I was able to write this script myself:
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) * new Vector2(1, 0);
Vector2 mousePosition2 = mousePosition + new Vector2(1, -4.74f);
transformPosition1.transform.position = mousePosition2;
This script changes the position of the object relative to the x-axis of the mouse. But I do not know how to limit its area and divide it into two players. Thank you in advance for your help. I apologize for my English. Please do not use complex language constructions in the response.
答案1
得分: 2
-
一种方法是将一张图片放在屏幕的上半部分,将另一张图片放在下半部分,并分配 EventSystem 来处理拖动。
-
另一种方法是计算鼠标位置,以确定它是否位于屏幕的上半部分或下半部分。
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); float y = mousePosition.y; if (y > Screen.height / 2 && y < Screen.height) { // 移动位于上半部分的玩家 } if (y > 0 && y < Screen.height / 2) { // 移动位于下半部分的玩家 }
英文:
-
One way would be putting one image to top half of the screen and other to bottom half and assign EventSystem to handle dragging.
-
Other way is to calculate the mouse position to see if it is within the top half or bottom half.
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); float y = mousePosition .y; if (y > Screen.height / 2 && y < Screen.height)// top half { // move the top side player } if (y > 0 && y < Screen.height / 2)// bottom half { // move the bottom side player }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论