【问题标题】:Detect If Two Buttons Are Held Down检测两个按钮是否被按住
【发布时间】:2022-01-01 02:16:30
【问题描述】:

我正在为安卓开发一款无尽的跑步游戏,并使用 UI 按钮来左右移动玩家。当我同时按下左右 UI 按钮时,我想让玩家跳跃。这是我的玩家移动脚本:

using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerMovement : MonoBehaviour
{
   
    public float speed = 15;
    public float diSpeed = 20; 
         
    public Rigidbody rb;
    CharacterController characterController;

    Vector3 moveVector = Vector3.zero;

    float horizontalInput;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void FixedUpdate()
    {
        Vector3 forwardMove = transform.forward * speed * Time.fixedDeltaTime;
        Vector3 horizontalMove = transform.right * moveVector.x * diSpeed * Time.fixedDeltaTime;
        rb.MovePosition(rb.position + forwardMove + horizontalMove);
    }

    void Update()
    {
       
        moveVector.x = CrossPlatformInputManager.GetAxis("Horizontal");
       
    }
}

代表 UI 按钮的游戏视图:

【问题讨论】:

    标签: c# android unity3d


    【解决方案1】:

    试试

    private float cooldownL;
    private float cooldownR;
    private bool isLeftPressed;
    private bool isRightPressed
    
    void Update(){
        cooldownR -= Time.deltaTime;
        cooldownL -= Time.deltaTime;
        if(cooldownR < 0){cooldownR = 0;}
        if(cooldownL < 0){cooldownL = 0;}
    
        if(isLeftPressed = true)
            movement = -1;
        }        
        if(isRightPressed = true)
            movement = 1;
        }
        if(cooldownL != 0 && cooldownR)
            // jump
        }
    }
    public void LeftPress(){
        isLeftPressed = true;
        cooldownL = 0.8f;
    }
    public void RightPress(){
        isRightPressed = true;
        cooldownR = 0.8f;
    }
    

    以下是如何为您的按钮分配脚本: 然后选择分配了您的脚本的对象,并在“无功能”下选择您的脚本名称,然后根据哪个按钮转到“leftPress()”或右。

    【讨论】:

    • 将 LeftPress 方法分配给左侧 UI 按钮,将 RightPress 方法分配给右侧 UI 按钮取决于什么样的游戏,运动变量只是一个占位符,你可以放下你的运动。
    • 如何将 leftpress 方法分配给 UIbutton??
    • 这很简单:您转到层次结构,然后选择您的按钮,在 Inspector 中您会看到“按钮”组件,向下滚动一点,您就会找到“OnClick”事件。创建一个新事件并拖动分配了脚本的对象。然后选择脚本,然后选择函数“leftPress()”
    • 看看更新后的答案,里面有图片
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2012-07-27
    相关资源
    最近更新 更多