【问题标题】:Unity2D shooting targets in order to random colors' match - C#Unity2D射击目标以随机颜色匹配 - C#
【发布时间】:2018-10-16 14:31:39
【问题描述】:

我正在尝试做一个包含任务的游戏。其中之一是按照随机生成​​的正确顺序拍摄彩色目标。我一直在检测玩家是否以正确的顺序击中目标。

假设我们有很多球,它们的颜色在 4 个值之间随机分配:BlueRedGreyPurple。我们向玩家展示了他需要击中它们的顺序,并且玩家尝试按照所述顺序射击目标。

示例:如果球出来了,BlueRedGreyPurple 玩家必须按顺序射球。

我对编程和 Unity 非常陌生,所以我不知道该怎么做。

我提供了用于随机分配颜色给精灵的代码,让您了解颜色的工作原理。

public Color[] Colors;

private void Start () 
{
    int color = Random.Range(0, Colors.Length);

    GetComponent<SpriteRenderer>().color = Colors[color];
}

【问题讨论】:

    标签: c# unity3d arraylist game-physics


    【解决方案1】:

    所以你需要确保玩家按正确的顺序点击颜色?

    首先,您的代码存在问题。 Colorize 是动词,只能用于函数和方法名,这就是为什么 StackOverflow 给它一个颜色,它认为它是一个函数。名字听起来是Colors。 (我知道,“s”在英语中听起来像“z”很奇怪,但有一个有趣的原因)。

    首先,像这样创建一个enum

    public class BallUtilities
    {
        enum BallColors { Red, Blue, Green, Yellow, Pink, Purple ... };
    
        public static Color32 ToColor(this BallColor ballColor) =>
        {
             switch (ballColor)
             {
                 case BallColor.Red:  return new Color32 (255, 50, 50);
                 case BallColor.Blue: return new Color32 (50,  50, 255);
                 case BallColor.Green: ...
                 .
                 .
                 .
                 (etc.)
             }
        }
    }
    

    现在,我们需要跟踪所有创建的球,所以:

    public class BallManager
    {
        public static List<BallColor> BallColorsSpawned = new List<BallColor>();
    }
    

    然后,将您当前的脚本更改为:

    public void Start()
    {
        Color = (BallColor)Random.Range(0, Enum.GetNames(typeof(BallColor)).Length - 1)
        GetComponent<SpriteRenderer>().Color = Color.ToColor();
        Ballmanager.SpawnBallsColor.Add(Color);
    }
    

    现在我们按照玩家需要击中它们的顺序列出了所有颜色。所以现在,无论玩家在哪里击球,都要做这样的事情:

    Ball ballHit = GetBallHit();   // Leaving it up to you to find out how to get whatever 
                                   // ball was just hit stored as a variable
    
    if (BallManager.BallColorsSpawned[0].Color == ballHit.Color)
    {
        if (BallManager.BallColorsSpawned.Length == 1)
            // That was the last ball remaining, so the player wins
        else BallManager.BallColorsSpawned.RemoveAt(0);  // Remove it as no longer important
    }
    else 
    {
        // Player hit the wrong ball, so the player loses
    }
    

    如果你不知道 enum 是什么或扩展方法或其他我用过的东西,那么暂时停止使用 Unity,并使用 Visual Studio 上的实践项目、在线教程和乔恩·斯基特 (Jon Skeet) 的 C# 深度剖析。在我安装 Unity 之前,我已经编写了几个月的 C# 代码。

    【讨论】:

      猜你喜欢
      • 2015-04-09
      • 2011-03-09
      • 2018-11-29
      • 1970-01-01
      • 2020-01-28
      • 2014-01-19
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      相关资源
      最近更新 更多