简体   繁体   English

我如何在 Unity3D 中进行触摸工作?

[英]How do I get touch working in Unity3D?

I'm making an Android app with Unity3D and it works with click detection already, but not with touch.我正在使用 Unity3D 制作一个 Android 应用程序,它已经可以用于点击检测,但不能用于触摸。 I need touch though for multitouch detection.我需要触摸进行多点触控检测。

What I want: I have my player and 2 images of arrows.我想要什么:我有我的播放器和 2 张箭头图像。 One arrow points right and one left.一个箭头指向右,一个指向左。 When I touch the left arrow the player should start moving left, when I touch the right arrow the player should start moving right.当我触摸左箭头时,玩家应该开始向左移动,当我触摸向右箭头时,玩家应该开始向右移动。

But how do I detect which arrow is touched (and held)?但是我如何检测哪个箭头被触摸(并保持)了? All the code I found on Google is too old and not working anymore.我在谷歌上找到的所有代码都太旧了,不再工作了。

I'm working with C# scripts and it's a 2D game.我正在使用 C# 脚本,它是一个 2D 游戏。

Klausar, what you're looking for is .........克劳萨尔,你要找的是…………

A BUTTON (!!!)一个按钮(!!!)

it's that easy!就这么简单!

  1. click "add Canvas".单击“添加画布”。 (You very likely want "scale to screen size" - select that option.) (您很可能想要“缩放到屏幕大小” - 选择该选项。)

  2. click "add Button".单击“添加按钮”。

  3. there is no "three" .. go drinking.没有“三”..去喝酒。

In your code, have a routine like this for the right-side button在您的代码中,为右侧按钮设置这样的例程

public void UserClickedRight()
 {
 Debug.Log("click right whoo!");
 }

and have a similar routine for the left-side button.并为左侧按钮提供类似的例程。

1. Go to your Button in the editor. 1. 转到编辑器中的Button

2. Simply drag the script to it and select UserClickedRight !! 2. 只需将脚本拖到它上面并选择UserClickedRight !!

You actually do not have to program buttons from scratch :)您实际上不必从头开始编写按钮 :)

This is a basic mechanism of Unity - drag a game object to a "slot" for it in the Editor.这是 Unity 的基本机制 - 在编辑器中将游戏对象拖到“插槽”中。

(The game object you drag, has the script in question on it.) (您拖动的游戏对象上有相关脚本。)

You DO NOT need to go to the level of touch handling to achieve a button!您无需达到触摸处理级别即可实现按钮!


Now you ask, what about "when holding down on the button"?现在你问,“按住按钮时”怎么样?

It's very easy, you just need to know a couple of things about the Unity "event" system.这很容易,您只需要了解有关 Unity“事件”系统的一些信息。

In Button , Unity have done all the work for "OnClick":Button ,Unity 已经完成了“OnClick”的所有工作:

在此处输入图片说明

Since "click" is common, they put that one right in the Inspector panel for you for convenience.由于“单击”很常见,为了方便起见,他们将其放在“检查器”面板中。

The good news is that Button has many more events you can use .好消息是Button更多您可以使用的事件

http://docs.unity3d.com/ScriptReference/UI.Button.html http://docs.unity3d.com/ScriptReference/UI.Button.html

My guess is you want to use OnPointerDown and OnPointerUp in your case.我的猜测是你想在你的情况下使用OnPointerDownOnPointerUp

To use the other events (which Unity did not bother putting in the Inspector panel) is very simple, you just要使用其他事件(Unity 没有费心将其放入 Inspector 面板)非常简单,您只需

1, make a script that references the events you want, 1,制作一个脚本,引用你想要的事件,

and,并且,

2, you put that script ON the button in question ... 2,您将该脚本放在有问题的按钮上......

it's that easy.就这么简单。

Step by step explanation:分步说明:

You're going to be using Unity's event system, so:您将使用 Unity 的事件系统,因此:

  using UnityEngine.EventSystems;

Next.接下来。 You know that a script normally starts like this...你知道一个脚本通常是这样开始的......

 public class FancyButton:MonoBehaviour

The "MonoBehaviour" part just means that it's ac# script which will be "driving a GameObject". “MonoBehaviour”部分只是意味着它将是“驱动游戏对象”的 ac# 脚本。

In this case we have to further alert the engine that you will be using those click events.在这种情况下,我们必须进一步提醒引擎您将使用这些点击事件。 So you add this.所以你加了这个。

,IPointerDownHandler,IPointerUpHandler

So far we have this到目前为止,我们有这个

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
    {

Now the easy part.现在是简单的部分。

You just type the two routines which Unity will run for you, when, those things happen.您只需键入 Unity 将为您运行的两个例程,当这些事情发生时。

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
  public void OnPointerDown(PointerEventData data)
  {
      Debug.Log("holy! someone put the pointer down!")
  }

  public void OnPointerUp(PointerEventData data)
  {
      Debug.Log("whoa! someone let go!")
  }
}

Now all you have to do is drop that script on the Button.现在您所要做的就是将该脚本放在按钮上。 Done!完成!

You can put that script on any button, where, you need that functionality.您可以将该脚本放在任何需要该功能的按钮上。

Next, click on Obi-wan to see where we're at so far!接下来,单击 Obi-wan 以查看我们目前所处的位置!

在此处输入图片说明

Finally, it sounds like you want to do something "when the button is being held down".最后,听起来您想在“按住按钮时”执行某些操作。 That's just a general programming issue - you'd have a boolean which you turn on and off as the button goes up and down .这只是一个一般的编程问题 -你有一个布尔值,当按钮上下时打开和关闭 Let's do it.让我们做吧。

    using UnityEngine;
    using System.Collections;
    using UnityEngine.EventSystems;
    
    public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
        {
        [System.NonSerialized] public bool mouseIsDownRightNow;
        
        public void OnPointerDown(PointerEventData data)
            {
            mouseIsDownRightNow = true;
            }
        
        public void OnPointerUp(PointerEventData data)
            {
            mouseIsDownRightNow = false;
            }
        }

You could access that variable from another script, or whatever you want.您可以从另一个脚本或任何您想要的脚本访问该变量。

Add the following if you want to run a routine while the button is down:如果要在按钮按下时运行例程,请添加以下内容:

    void Update()
        {
        if (buttonIsDownRightNow) WhileButtonIsDown();
        }
    private void WhileButtonIsDown()
        {
        Debug.Log("THE BUTTON IS DOWN! WHOA!");
        }
    

Try that and watch the console as you hold the button down and up.尝试这样做并在按住按钮时观察控制台。

Here's an example of something like continually increasing a value while the button is down:这是一个在按钮按下时不断增加值的示例:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
    {
    [System.NonSerialized] public bool buttonIsDownRightNow;
    private int countSomething;
    
    public void OnPointerDown(PointerEventData data)
        {
        buttonIsDownRightNow = true;
        }
    
    public void OnPointerUp(PointerEventData data)
        {
        buttonIsDownRightNow = false;
        }
    
    private void WhileButtonIsDown()
        {
        ++countSomething;
        }
    
    void Update()
        {
        if (buttonIsDownRightNow) WhileButtonIsDown();
        
        Debug.Log("value is now " +countSomething.ToString());
        }
    }

That's all there is to it.这就是它的全部内容。 Once you really understand events in Unity, there is not much more to learn about Unity.一旦你真正理解了 Unity 中的事件,就没有更多关于 Unity 的知识了。

The only other important topics are Mecanim, shader writing, touch, coroutines, threading, PhysX, native plugins, sprites, networking, dynamic mesh, navigation, VR, AR, animation, inverse kinematics, particles, terrain, IAP, lighting, baking, shadows, MMP, character controllers, and audio.唯一的其他重要主题是 Mecanim、着色器编写、触摸、协程、线程、PhysX、本机插件、精灵、网络、动态网格、导航、VR、AR、动画、反向运动学、粒子、地形、IAP、照明、烘焙、阴影、MMP、角色控制器和音频。 Enjoy!享受!

You should firsty read this .你应该首先阅读这个 What you are trying to do is actually simple:你想要做的其实很简单:

foreach (Touch touch in Input.touches) {

    if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
        if (guiTexture1.HitTest(touch.position)) {

            // Maybe move left
        }
        if (guiTexture2.HitTest(touch.position)) {

            // Maybe move right
        }
    }
}

Edit 1: this code now checks which image is being pressed编辑 1:此代码现在检查正在按下哪个图像
Edit 2: Added multitouch support编辑 2:添加了多点触控支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM