MENU
Главная » Файлы » Скрипты

Оценка уровня и системы для Unity3D.
08.05.2012, 07:13

Как использовать: Скопируйте и вставьте этот код в новый
сценарий C # с именем Scoring.cs, а затем наложить скрипт на плеере объект,
графический объект, или что будет следить за счетом.



Как это работает: уровень игрока и оценка отслеживаются
путем двух простых целочисленных переменных. Оценка начинается с 0, а уровень
начинается 1. Вы можете изменить эти начальные значения, назначив новые и в
некоторых других скриптах, которые полезны при восстановлении ранее сохраненной
игры.



Список оценок сохраняется и по сравнению друг с другом
Update (), чтобы увидеть, если у игрока достаточно очков, чтобы выровнять.
Уровень может быть как очки, набранные в Space Invaders или более сложные, такие
как отслеживание опыт в RPG.



Обычно в видео игры, первые несколько уровней имеют
нелинейный прогресс или количество баллов, необходимое на уровень. Вы можете
указать что это нелинейная прогрессия, введя баллы, необходимых для каждого из
первых уровнях в Inspector. Взгляните на m_nextLevelScore переменной, которое
выставляется в Unity3D инспектор в виде массива целых чисел. Как только Вы
определили первые значения точки (значения по умолчанию приведены в исходном
коде), вы указываете, сколько, очков, требуется на каждом уровне за нелинейной
прогрессии.



Взгляните на код, в верхней части класса, который вы
увидите, что m_nextLevelScore переменную имеет несколько значений по умолчанию.
Чтобы перейти от уровня 1 к уровню 2 требуется 3000 очков. От уровня 2 на
уровень 3, 7000 точек не требуется. И так далее. Когда вы нажмете на последнее
значения в списке, 80000 очков, становится линейной прогрессией, поэтому
m_nextLevelScoreProgression переменную  берет на себя, требуя 100 000 очков за уровень
после 10-го уровня, т.е. 80 000 пунктов. Каждый уровень с тех пор потребует
дополнительных 100,000 очков.



Максимальный уровень, который может быть достигнут обрабатывается
m_maximumLevel переменной. По умолчанию установлено значение 100, но вы можете
установить любое значение, которое вы хотите. Функция, которая проверяет
уровень, CheckForLevelUp () является виртуальной, так что вы можете изменить
его в наследуемом классе вместо этого обращаться с компьютерной прогрессии.



Вы можете задать звуковые эффекты, которые будут играть,
когда игрок уровня с использованием m_nextLevelSound переменной, который
подвергается в инспекторе. Можно указать несколько звуков, или только один, или
даже вообще ни одной. Если у вас есть только один уровень вверх звуковой эффект
тот же, будет использоваться неоднократно. Если у Вас есть больше чем один, но
не отдельные звуковые эффекты для каждого отдельного уровня, то последние
звуковые эффекты, указанные в списке будут использованы для каждого уровня за
количество звуковых эффектов.



Предположения: отрицательные уровни не поддерживаются.
Выравнивание вниз, не поддерживается. Отрицательные оценки работы, но,
вероятно, не должны использоваться.



Примерно так выглядит перевод с сайта otakunozoku на русском =)


Code
/*-----------------------------------------------------------------------------
  * Scoring.cs - Keeps track of the player's score and levels up as required.
  * Copyright (C) 2010 Justin Lloyd
  * http://www.otakunozoku.com/
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 3 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU lesser General Public License
  * along with this library. If not, see <http://www.gnu.org/licenses/>.
  *
-----------------------------------------------------------------------------*/

using UnityEngine;
using System;
using System.Text;

[RequireComponent(typeof(AudioSource))]
public class Scoring : MonoBehaviour
{
  /// <summary>
  /// Audio clips to play for each level up sound.
  /// </summary>
  public AudioClip[] m_nextLevelSound;

  /// <summary>
  /// Maximum permitted level.
  /// </summary>
  public int m_maximumLevel = 100;

  /// <summary>
  /// The list of scores required to advance to the next level.
  /// </summary>
  public int[] m_nextLevelScore = { 0, 3000, 7000, 12000, 18000, 25000, 34000,
44000, 56000, 69000, 80000 };

  /// <summary>
  /// The number of required points to score to advance to the next level once
the score has gone beyond the provided list of points.
  /// </summary>
  public int m_nextLevelScoreProgression = 100000;

  /// <summary>
  /// The player's current score.
  /// </summary>
  private int m_score = 0;

  /// <summary>
  /// The player's current level.
  /// </summary>
  private int m_level = 1;

  /// <summary>
  /// The minimum level permitted.
  /// </summary>
  private const int MinimumLevel = 1;

  /// <summary>
  /// The player's score.
  /// </summary>
  public int Score
  {
  get
  {
  return m_score;
  }

  set
  {
  m_score = value;
  }

  }

  /// <summary>
  /// Adjust the score by the specified number of points. Negative values
  /// will subtract points.
  /// </summary>
  /// <param name="points" />Number of points to adjust the current score
by.</param>
  public void AdjustScore(int points)
  {
  m_score += points;
  }

  /// <summary>
  /// Adjust the current level by the specified number of levels. Negative
  /// values will subtract levels. Does not adjust the score to match. The
  /// new level will be clamped to within the maximum permitted level.
  /// </summary>
  /// <param name="levels" />Number of levels to adjust the current level
by.</param>
  public void AdjustLevel(int levels)
  {
  m_level = Mathf.Clamp(m_level + levels, MinimumLevel, m_maximumLevel);
  }

  /// <summary>
  /// The player's current level. Specifying a new level will ensure that the
  /// new level is clamped to the maximum permitted level.
  /// </summary>
  public int Level
  {
  get
  {
  return m_level;
  }

  set
  {
  m_level = Mathf.Clamp(value, MinimumLevel, m_maximumLevel);
  }

  }

  /// <summary>
  /// Play the audio for level up sound.
  /// </summary>
  public void PlayNextLevelSound()
  {
  int levelUpIndex = Mathf.Clamp(m_level, MinimumLevel,
m_nextLevelSound.Length - 1) - 1;
  if (m_nextLevelSound[levelUpIndex] == null)
  {
  return;
  }

  this.audio.PlayOneShot(m_nextLevelSound[levelUpIndex]);
  }

  /// <summary>
  /// Checks for completion of the current level and advances to the next
  /// level if the score is high enough.
  /// </summary>
  public virtual void CheckForLevelUp()
  {
  // if we have reached the maximum level, do nothing
  if (m_level >= m_maximumLevel)
  {
  return;
  }

  // check for the next required score
  int nextLevelScore = 0;
  // if there are no more scores in the level score progression array
  // switch over to linear progression
  // otherwise, use the non-linear progression
  if (m_level >= m_nextLevelScore.Length)
  {
  nextLevelScore = (m_level - m_nextLevelScore.Length + 1) *
m_nextLevelScoreProgression;
  }
  else
  {
  nextLevelScore = m_nextLevelScore[m_level];
  }

  // if we have the required score to level up, advance to the next level
  if (m_score >= nextLevelScore)
  {
  m_level = Math.Min(m_level + 1, m_maximumLevel);
  PlayNextLevelSound();
  }

  }

  void Update()
  {
  CheckForLevelUp();
  }

}
Категория: Скрипты | Добавил: DeMaN_74
Просмотров: 4532 | Загрузок: 0 | Рейтинг: 5.0/4
Всего комментариев: 0
Добавлять комментарии могут только зарегистрированные пользователи.
[ Регистрация | Вход ]
Хостинг от uCoz