c# - 在 Unity C# 中通过一键式游戏拖动控件和跳转

标签 c# ios unity3d mobile

我正在尝试让触摸控件适用于 iOS,我想要的结果是向左拖动向左移动,向右拖动向右移动并点击跳转。目前这些功能确实有效,但如果我不想跳跃而只想拖动角色,则会在触摸屏幕时首先跳跃。有没有办法我可以得到我想要的结果我在下面添加了我的代码。我希望第一次触摸只是注册拖动,当玩家抬起然后点击或双击时,角色会跳跃。提前致谢。

//Mobile Touch Drag Controls
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            // Get movement of the finger since last frame
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

            // Move object across X plane
            transform.Translate(touchDeltaPosition.x * speed, 0, 0);
        }
    }

    ////Mobile Touch To Jump
    {
        if (Input.GetMouseButtonDown(0))
        {

            transform.Translate(Vector3.up * jumpForce * Time.deltaTime, Space.World);

        }

最佳答案

当按钮按下时,无法知道玩家想要做什么。你应该在手指抬起时跳跃。

一个简单的解决方案是使用 bool 值来了解玩家在手指释放之前是否已经移动。如果是,你不想跳

public class PlayerController // Or whatever name your class has
{
    private bool _moved;

    private void Update()
    {
        //Mobile Touch Drag Controls
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            // Get movement of the finger since last frame
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;

            // Move object across X plane
            transform.Translate(touchDeltaPosition.x * speed, 0, 0);
            _moved = true; // Remember that the player moved
        }


        ////Mobile Touch To Jump
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
        {
            if(!_moved) // Only jump if we didnt move
            {
                transform.Translate(Vector3.up * jumpForce * Time.deltaTime, Space.World);
            }
            _moved = false;
        }
    }
}

我假设此代码进入您的更新功能。这可以正常工作,但如果您想尝试,这里有一个更优雅的解决方案:

你的类可以实现 IDragHandler 和 IEndDragHandler (除其他外,寻找扩展 IEventSystemHandler 的所有可能性)

当您实现这些时,您可以覆盖在用户触摸屏幕时调用的函数,例如 public void OnDrag(PointerEventData eventData)
有了这个,您不必再使用更新功能

关于c# - 在 Unity C# 中通过一键式游戏拖动控件和跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372270/

相关文章:

c# - 如何检查播放器和 Unity 中特定 TileBase 对象之间的碰撞?

c# - 如何在不丢失纵横比的情况下在 Unity 中拉伸(stretch)某些东西?

c# - 有什么方法可以阻止光线转换穿过物体吗?

c# - EF 中的常量导致异常

c# - 是否可以在两个 excel 工作表之间设置外键?

C# - 验证模拟(MoQ)属性的方法是用部分字符串作为参数调用的

ios - Swift 中的 PFQuery

c# - IList有没有类似ForEach的方法?

ios - 使用 AlamoFire 发出 HTTP 请求会导致 EXC_BAD_ACCESS

ios - 搜索栏搜索号码,而不仅仅是联系人姓名