首页 > 解决方案 > 我的脚本让玩家连续跳跃,我想让它跳跃一次或两次

问题描述

我试图为我的项目制作一个运动脚本,但我遇到了问题。现在代码在手机和电脑上运行良好,但只有一个小问题我无法真正解决,基本上我被卡住了。对于移动设备,如果您按下触摸屏,播放器将使用速度并上升,直到您将手指从屏幕上移开。我真正想要的是当手指触摸手机的显示屏而不是在天堂的 Y 轴上移动时,让某些东西最多跳一次或两次。

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

public class PlayerBehaviour : MonoBehaviour
{
    /// <summary>
    /// A reference to the rigidbody component
    /// </summary>
    private Rigidbody rb;

    [Tooltip("How fast is goes side ways")]
    public float dodgeSpeed;
    
    public float jumpForce;
   
    [Tooltip("How fast is goes forward!")]
   // [Range(0,20)]
    public float rollSpeed;
    float dirX;
 
 
  

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        
    }

    // Update is called once per frame

    void Update()
    {
        dirX = Input.acceleration.x * dodgeSpeed;
       
        var horizontalSpeed = Input.GetAxis("Horizontal") * dodgeSpeed;

       
        if (Input.GetKeyDown(KeyCode.Space))
        {
                rb.velocity = new Vector3(horizontalSpeed + dirX, jumpForce, rollSpeed);
           
        }
          else 
        {
            rb.AddForce(horizontalSpeed + dirX, 0, rollSpeed);
        }
        
     
        if (Input.touchCount > 0)
        {
            
                rb.velocity = new Vector3(horizontalSpeed + dirX, jumpForce, rollSpeed);

        }
        else
        {
            rb.AddForce(horizontalSpeed + dirX, 0, rollSpeed);
        }
    }
}

标签: c#unity3d

解决方案


您可能想使用TouchPhase。在更新中,您可以检查阶段并仅在它刚刚开始时才跳转:

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
    rb.velocity = new Vector3(horizontalSpeed + dirX, jumpForce, rollSpeed);
}

推荐阅读