【问题标题】:My script is making the player to jump continuously and I want to make it to jump once or twice我的脚本让玩家连续跳跃,我想让它跳跃一次或两次
【发布时间】:2021-10-29 22:22:37
【问题描述】:

我试图为我的项目制作一个移动脚本,但我遇到了问题。现在代码在手机和电脑上运行良好,但只有一个小问题我无法真正解决,基本上我被卡住了。对于移动设备,如果您按下触摸屏,播放器将使用速度并上升,直到您将手指从屏幕上移开。我真正想要的是当手指触摸手机的显示屏而不是在天上的 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


【解决方案1】:

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

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

【讨论】:

  • 是的,解决了我一半的问题(如果我将手指放在屏幕上跳跃一次),但如果我仍然连续按 10 次,播放器仍然会上升。我真正想要的是当玩家在地面上时跳跃一次或最多两次。现在,如果我在播放器在空中时按下屏幕,它仍在上升,而不是什么都不做......
  • @andr3y38 最好在一个单独的问题中提出,因为这是一个单独的问题。但是不要打扰询问和关闭重复 - 使用这些作为参考:stackoverflow.com/questions/54490384/…answers.unity.com/questions/1411531/… 总而言之,您需要检测与地面的碰撞并记录您在不接触地面的情况下跳跃的次数,并且当计数器大于一或二时停止增加速度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
相关资源
最近更新 更多