检测用第一根手指按下按钮,但如果用更多手指按下则不会检测 Unity

2024-03-10

In my 平台游戏我有一个球角色,可以通过按来移动三个按钮: a “向右移”按钮使其向右移动,a“向左移动”将其向左移动,然后"Jump"按钮会给球施加垂直力,使其跳跃。

这是我用于运动控制的代码 -一切都按其应有的方式进行:

Script Move2D:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move2D : MonoBehaviour
{
    public float moveSpeed = 7f;
    public float jumpSpeed = 7F;
    public bool isGrounded = false;

    public Rigidbody2D rigidbody;

    private Vector2 currentMoveDirection;

    private void Awake()
    {
        rigidbody = GetComponent<Rigidbody2D>();
    }

    public void Jump()
    {
        if (isGrounded)
        {
            rigidbody.AddForce(new Vector3(0f, jumpSpeed), ForceMode2D.Impulse);
        }
    }
    public void JumpHigher()
    {
        rigidbody.AddForce(new Vector3(0f, 12), ForceMode2D.Impulse);
    }

    private void FixedUpdate()
    {
        rigidbody.velocity = currentMoveDirection * moveSpeed + Vector2.up * rigidbody.velocity.y;
    }

    public void TriggerMoveLeft()
    {
        currentMoveDirection += Vector2.left;
    }

    public void StopMoveLeft()
    {
        currentMoveDirection -= Vector2.left;
    }

    public void TriggerMoveRight()
    {
        currentMoveDirection += Vector2.right;
    }

    public void StopMoveRight()
    {
        currentMoveDirection -= Vector2.right;
    }
}

Script 继续按钮:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ContinuesButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [SerializeField] private Button targetButton;

    [SerializeField] private Move2D playerMovement;

    [SerializeField] private bool movesLeft;

    private readonly bool isHover;

    private void Awake()
    {
        if (!targetButton) targetButton = GetComponent<Button>();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        if (movesLeft)
        {
            playerMovement.TriggerMoveLeft();
        } else
        {
            playerMovement.TriggerMoveRight();
        }
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (movesLeft)
        {
            playerMovement.StopMoveLeft();
        } else
        {
            playerMovement.StopMoveRight();
        }
    }
}

正如你所看到的,我是每次按下按钮时都会施加力。通过这样做,我意识到玩家可以通过多种方式“作弊”.

平台上有很多很难通过的障碍,因为速度刚刚好。通过用两根手指按同一个按钮,我会给球添加双重水平力,它会去快两倍, and 更容易通过关卡.

此外,在某些情况下,玩家有时间跳两次 and 走得更高比正常情况下的情况要好。

我怎样才能避免这两个问题?

任何帮助甚至任何一点信息都非常感谢!


适合您当前方法的一个简单方法是在此脚本中添加一个布尔字段,用于跟踪当前是否按住按钮。就像是private bool buttonHeld;

每当OnPointerDown被称为和buttonHeld == false,将其设置为 true 并调用您的命令,否则不执行任何操作。而对于OnPointerUp, if buttonHeld == true,将其设置为 false 并使您的运动停止。 并且为了安全起见,在void OnDisable(),将其设置为 false。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检测用第一根手指按下按钮,但如果用更多手指按下则不会检测 Unity 的相关文章

随机推荐