【问题标题】:How to make a method work in a period of time in C# UnityC# Unity中如何让一个方法在一段时间内工作
【发布时间】:2015-03-07 00:43:52
【问题描述】:

我一直在为我的这段代码苦苦挣扎。 我为我的玩家提供了一种方法,当它收集到一定数量的收藏品时,它会变得更快。但我希望我的播放器在一定时间内(例如 3 秒)跑得更快。并且计数器(用于收藏品)必须回到零,因此当玩家再次收集一定数量的收藏品时,它会再次更快,等等。

我的所有 PowerUp 都有一个类和一个不同的类:从 PowerUp 继承的 Speder。 当收集到一定数量的收藏品时,速度变量在我的玩家脚本中:Player0。

加电

using UnityEngine;
using System.Collections;

public class PowerUp : MonoBehaviour
{
  public static int counter = 0;

  void OnTriggerEnter2D(Collider2D other)
  {
    if (other.tag == "Player")
    {
      Speder.BoostThaSpeed();
      Destroy(this.gameObject);
      counter++;

      if (counter == 3)
      {
        counter = 0;
      }
    }
  } 
}

斯佩德

using UnityEngine;
using System.Collections;

public class Speder : PowerUp
{
  public static void BoostThaSpeed()
  {
    if (counter == 2)
    {
      Player0.speed = Player0.speed * 2;
    }

    else if (counter < 2)
    {
      Player0.speed = Player0.speed = 3.5f;
    }
  }
  void OnGUI()
  {
    GUI.Box(new Rect(750, 0, 130, 20), "Counter:" + counter);
  }
}

玩家0

using UnityEngine;
using System.Collections;

public class Player0 : MonoBehaviour
{

  // SPEEDVARIABLES
  public static float speed = 3.5f;

void Update()
  {
 // MOVING CODE

    if (Input.GetKey(KeyCode.LeftArrow))
    {
      rigidbody2D.velocity = new Vector2(-speed, rigidbody2D.velocity.y);   // - speedForce (om naar links te gaan)
      transform.localScale = new Vector3(-0.3f, 0.3f, 0.3f);   
    }

    else if (Input.GetKey(KeyCode.RightArrow))
    {
      rigidbody2D.velocity = new Vector2(speed, rigidbody2D.velocity.y);   // + speedforce (om naar rechts te gaan)
      transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
    }

    else
    {
     rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y);
    }
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以在更新方法中使用 Time.deltaTime 来减少变量

    将 SpeedboostTimeRemaining 属性添加到 Speder 并将其设置为任意时间,例如 BoostThaSpeed 方法中的 10

    然后将更新方法添加到Speder并放入

    if(SpeedboostTimeRemaining > 0)
    {
        SpeedboostTimeRemaining -= Time.deltaTime
        if(SpeedboostTimeRemaining < 0)
        {
            SpeedboostTimeRemaining = 0;
            Player0.speed = 3.5f;
        }
    }
    

    【讨论】:

    • 虽然,我认为你需要重构以减少对全局对象的使用
    • 你让我开心,先生!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多