简体   繁体   English

unity-移动触摸控件在2D游戏中拖动游戏对象

[英]unity - mobile touch control to drag gameobject in 2D game

I wanted to find out what is the best-practice method to use for touch controls for mobile 2D games, specifically dragging a paddle for breakout/arkanoid style games. 我想找出用于移动2D游戏的触摸控件的最佳实践方法是什么,特别是拖动突围/ arkanoid风格游戏的手柄。 Would be surprised if there are no easy built in Unity facility to do this as I would have thought this would have been a standard feature given the popularity of mobile games. 如果没有简单的Unity内置功能可以做到这一点,我会感到惊讶,因为我认为,鉴于手机游戏的普及,这将是标准功能。 Any advice or links to tutorials, especially dragging game objects, would be greatly appreciated. 任何建议或教程链接,特别是拖动游戏对象,将不胜感激。 Thanks. 谢谢。

My advice would be to use the unity UI features (introduced in Unity 4.6) using a script like this one : 我的建议是使用像这样的脚本来使用统一的UI功能(在Unity 4.6中引入):

public class DragControl : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool m_Used;
    private Vector3 m_MouseStartPosition;
    private Vector3 m_ItemStartPosition;

    public void Start()
    {
        m_Used = false;
    }

    public void Update()
    {
        if(m_Used)
        {
            GetComponent<RectTransform>().anchoredPosition = new Vector2(m_ItemStartPosition.x + (Input.mousePosition.x - m_MouseStartPosition.x), m_ItemStartPosition.y + (Input.mousePosition.y - m_MouseStartPosition.y));
            // or you can set the y value to m_ItemStartPosition.y only if you don't want the paddle to move on Y axis
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        m_Used = true;
        m_MouseStartPosition = Input.mousePosition;
        m_ItemStartPosition = GetComponent<RectTransform>().anchoredPosition;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        m_Used = false;
    }
}

For this to work you have to enable the UI item raycasting (keep "Raycast Target" checked) and nothing blocking the raycast being over your item in the UI layers. 为此,您必须启用UI项射线广播(保持选中“ Raycast Target”),并且在UI层中什么也不能阻止射线广播超出您的项目。

Also note that if you don't need it you can disable mutli touch input using Input.multiTouchEnabled = false; 还要注意,如果不需要,可以使用Input.multiTouchEnabled = false;禁用多点触摸输入Input.multiTouchEnabled = false; .

An easy solution would be to import the now standard (Unity 5?) "DragRigidbody" script and attach it to your Game Object. 一个简单的解决方案是导入现在标准的(Unity 5?)“ DragRigidbody”脚本并将其附加到您的游戏对象。 Just make sure your object has a RigidBody Component attached to it (which I would assume your paddle object would have already). 只要确保您的对象具有附加的RigidBody组件(我认为您的桨状对象已经具备)。

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

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