如何在Unity3D中用手指控制对象?

huangapple go评论61阅读模式
英文:

How to control an object with a finger in Unity3D?

问题

我是新手程序员。我正在为智能手机编写一个简单的游戏(我认为很多人知道它叫做“乒乓球”)。这是一个供两人玩的游戏。我需要将屏幕分成两个区域。每个人都应该能够用手指沿x轴控制对象。因此,对象只会沿x轴改变位置。

这是我的游戏 如何在Unity3D中用手指控制对象?

我能够自己编写这个脚本:

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.

here's my game 如何在Unity3D中用手指控制对象?

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

  1. 一种方法是将一张图片放在屏幕的上半部分,将另一张图片放在下半部分,并分配 EventSystem 来处理拖动。

  2. 另一种方法是计算鼠标位置,以确定它是否位于屏幕的上半部分或下半部分。

     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) {
     // 移动位于下半部分的玩家
     }
    
英文:
  1. One way would be putting one image to top half of the screen and other to bottom half and assign EventSystem to handle dragging.

  2. 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 &gt; Screen.height / 2 &amp;&amp; y &lt; Screen.height)// top half {
    // move the top side player
    }
    if (y &gt; 0 &amp;&amp; y &lt; Screen.height / 2)// bottom half {
    // move the bottom side player
    }
    

huangapple
  • 本文由 发表于 2023年2月6日 03:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定