Четверг, 18 Апреля 2024, 10:43

Приветствую Вас Гость

[ Новые сообщения · Игроделы · Правила · Поиск ]
  • Страница 1 из 1
  • 1
Форум игроделов » Движки для разработки игр и сложные системы разработки » Unity » Проблема со скриптом
Проблема со скриптом
VasaGameDevДата: Вторник, 06 Января 2015, 10:33 | Сообщение # 1
почетный гость
Сейчас нет на сайте
Привет всем! Нашел хороший скрипт на камеру и он мне понравился. Захотел глянуть на код скрипта и тут я кое что не понял!

Чтобы скрипт работал надо сделать вот такое дерево



Вот скрин скрипта в инспекторе

Как я понял в скрипте должна быть переменная Target, но в скрипте я ее не увидел!

Код

using UnityEngine;

public class FreeLookCam : AbstractTargetFollower
{
  // This script is designed to be placed on the root object of a camera rig,
  // comprising 3 gameobjects, each parented to the next:

  //  Camera Rig
  //   Pivot
  //    Camera

     [SerializeField] private float moveSpeed = 1f;      // How fast the rig will move to keep up with the target's position.
     [Range(0f,10f)]
  [SerializeField] private float turnSpeed = 1.5f;    // How fast the rig will rotate from user input.
  [SerializeField] private float turnSmoothing = 0.1f;// How much smoothing to apply to the turn input, to reduce mouse-turn jerkiness
  [SerializeField] private float tiltMax = 75f;       // The maximum value of the x axis rotation of the pivot.
     [SerializeField] private float tiltMin = 45f;       // The minimum value of the x axis rotation of the pivot.
     [SerializeField] private bool lockCursor = false;   // Whether the cursor should be hidden and locked.
      
     private float lookAngle;                            // The rig's y axis rotation.
     private float tiltAngle;                            // The pivot's x axis rotation.
     private Transform pivot;                            // The pivot.
     private ThirdPersonCharacter character;             // Reference to the character controller.
     private const float LookDistance = 100f;            // How far in front of the pivot the character's look target is.
  private float smoothX = 0;
  private float smoothY = 0;
  private float smoothXvelocity = 0;
  private float smoothYvelocity = 0;
   
  void Awake() {
         // Lock or unlock the cursor.
   Screen.lockCursor = lockCursor;

   // The pivot should be the first and only child gameobject of the rig.
   pivot = transform.GetChild(0);

  }

  void Update() {

   HandleRotationMovement();
  }

  protected override void FollowTarget (float deltaTime)
  {
   // Move the rig towards target position.
   transform.position = Vector3.Lerp(transform.position, target.position, deltaTime * moveSpeed);
  }

  void HandleRotationMovement()
  {
   // Read the user input
   var x = CrossPlatformInput.GetAxis ("Mouse X");
   var y = CrossPlatformInput.GetAxis ("Mouse Y");

   // smooth the user input
   if (turnSmoothing > 0)
   {
    smoothX = Mathf.SmoothDamp(smoothX, x, ref smoothXvelocity, turnSmoothing);
    smoothY = Mathf.SmoothDamp(smoothY, y, ref smoothYvelocity, turnSmoothing);
   } else {
    smoothX = x;
    smoothY = y;
   }

   // Adjust the look angle by an amount proportional to the turn speed and horizontal input.
   lookAngle += smoothX * turnSpeed;

   // Rotate the rig (the root object) around Y axis only:
   transform.rotation = Quaternion.Euler (0f, lookAngle, 0f);

   #if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
   // For tilt input, we need to behave differently depending on whether we're using mouse or touch input:
   // on mobile, vertical input is directly mapped to tilt value, so it springs back automatically when the look input is released
   // we have to test whether above or below zero because we want to auto-return to zero even if min and max are not symmetrical.
   if (y>0) tiltAngle = Mathf.Lerp(0,-tiltMin, smoothY);
   if (y<=0) tiltAngle = Mathf.Lerp (0,tiltMax, -smoothY);
   #else
   // on platforms with a mouse, we adjust the current angle based on Y mouse input and turn speed
   tiltAngle -= smoothY * turnSpeed;
   // and make sure the new value is within the tilt range
   tiltAngle = Mathf.Clamp(tiltAngle, -tiltMin, tiltMax);
   #endif

   // Tilt input around X is applied to the pivot (the child of this object)
   pivot.localRotation = Quaternion.Euler(tiltAngle, 0f, 0f);
   
  }

}


Как же мне получить доступ к Target?
OtinagiДата: Вторник, 06 Января 2015, 11:20 | Сообщение # 2
постоянный участник
Сейчас нет на сайте
Возможно, она присутствует в родительском классе AbstractTargetFollower.

«Смерти меньше всего боятся те люди, чья жизнь имеет наибольшую ценность.»
Иммануил Кант
KernelTrueДата: Понедельник, 12 Января 2015, 08:47 | Сообщение # 3
был не раз
Сейчас нет на сайте
Цитата Otinagi ()
Возможно, она присутствует в родительском классе AbstractTargetFollower.

Более того не возможно, а точно присутствует smile

ТС, почитай про наследование.
dimanmonsterДата: Суббота, 24 Января 2015, 09:35 | Сообщение # 4
почетный гость
Сейчас нет на сайте
VasaGameDev,Хороший скрипт, но я тоже не понял как сделатьTarget публичной переменной! Может у кого то есть идеи?
MANMANAДата: Суббота, 24 Января 2015, 11:17 | Сообщение # 5
почти ветеран
Сейчас нет на сайте
смотри в родительском классе (скрипте) AbstractTargetFollower вот такую строку:

Код
[SerializeField] protected Transform target;                      // The target object to follow


на будущее: [SerializeField] - это во многих случаях лучше, чтобы видеть и изменять переменную в редакторе, чем просто public, тем более через сериализацию можно сделать видимыми защищенные, приватные и т.д. переменные

p.s. то, что вы не обратили внимание на
Код
public class FreeLookCam : AbstractTargetFollower
- плохо :(, поскольку вы проскочили мимо наследования классов. Рекомендую книгу "Файн Я. - Программирование на Java для детей, родителей, дедушек и бабушек - 2011", правда она по Джаве. Не смейтесь... очень доходчиво объясняются азы ООП.


http://www.3dbuffer.com/ Текстуры, Unity3D, Blender: Эффекты, скрипты, моделирование, текстурирование, скульптинг
VKонтакте 3Dbuffer

Последнее:

Новый раздел "Текстуры"

Как запатентовать, защитить техническое решение, игру, идею


Сообщение отредактировал MANMANA - Суббота, 24 Января 2015, 11:24
dimanmonsterДата: Суббота, 24 Января 2015, 13:37 | Сообщение # 6
почетный гость
Сейчас нет на сайте
Или я слепой или что то другое, но я не вижу эту строку

Код

[SerializeField] protected Transform target;                // The target object to follow


За книгу спс! Будет время почитаю!
MANMANAДата: Суббота, 24 Января 2015, 15:53 | Сообщение # 7
почти ветеран
Сейчас нет на сайте
в каком классе ищешь?
в текущем?

Не видя полного комплекта скриптов, не могу указать, где именно искать...
если речь идет вот про набор скриптов, обсуждаемый здесь, то я сказал, что искать нужно не в текущем скрипте, а в скрипте(классе), от которого наследуется текущий класс(скрипт).

p.s. и не откладывайте на потом чтение книг. прочитав про наследование классов вы все поймете

если не видите в упор, то найдите у себя в проекте и выложите сюда скрипт под названием "AbstractTargetFollower", вместе посмотрим


http://www.3dbuffer.com/ Текстуры, Unity3D, Blender: Эффекты, скрипты, моделирование, текстурирование, скульптинг
VKонтакте 3Dbuffer

Последнее:

Новый раздел "Текстуры"

Как запатентовать, защитить техническое решение, игру, идею
dimanmonsterДата: Суббота, 24 Января 2015, 16:10 | Сообщение # 8
почетный гость
Сейчас нет на сайте
Нашел скрипт и эту строку

Код

using UnityEngine;

public abstract class AbstractTargetFollower : MonoBehaviour
{
     public enum UpdateType                    // The available methods of updating are:
     {
         Auto,                    // Let the script decide how to update
         FixedUpdate,                    // Update in FixedUpdate (for tracking rigidbodies).
         LateUpdate,                    // Update in LateUpdate. (for tracking objects that are moved in Update)
     }
      
     [SerializeField] protected Transform target;                // The target object to follow
     [SerializeField] private bool autoTargetPlayer = true;    // Whether the rig should automatically target the player.
     [SerializeField] private UpdateType updateType;           // stores the selected update type

  virtual protected void Start() {
         // if auto targeting is used, find the object tagged "Player"
   // any class inheriting from this should call base.Start() to perform this action!
         if (autoTargetPlayer) {
    FindAndTargetPlayer();
   }

  }
   
  void FixedUpdate() {

         // we update from here if updatetype is set to Fixed, or in auto mode,
   // if the target has a rigidbody, and isn't kinematic.
   if (updateType == UpdateType.FixedUpdate || updateType == UpdateType.Auto && (target.rigidbody != null && !target.rigidbody.isKinematic)) {
    if (autoTargetPlayer && !target.gameObject.activeSelf) {
     FindAndTargetPlayer();
    }
    FollowTarget(Time.deltaTime);
   }
  }

  void LateUpdate() {

   // we update from here if updatetype is set to Late, or in auto mode,
   // if the target does not have a rigidbody, or - does have a rigidbody but is set to kinematic.
   if (updateType == UpdateType.LateUpdate || updateType == UpdateType.Auto && (target.rigidbody == null || target.rigidbody.isKinematic)) {
    if (autoTargetPlayer && !target.gameObject.activeSelf) {
     FindAndTargetPlayer();
    }
    FollowTarget(Time.deltaTime);
   }
  }
   

  protected abstract void FollowTarget(float deltaTime);

  public void FindAndTargetPlayer() {

         // only target if we don't already have a target
   if (target == null) {
    // auto target an object tagged player, if no target has been assigned
    var targetObj = GameObject.FindGameObjectWithTag("Player");  
    if (targetObj) {
     target = targetObj.transform;
    }
   }
  }

  public void SetTarget (Transform newTransform) {
   target = newTransform;
  }
}

MANMANAДата: Суббота, 24 Января 2015, 16:25 | Сообщение # 9
почти ветеран
Сейчас нет на сайте
и? smile

http://www.3dbuffer.com/ Текстуры, Unity3D, Blender: Эффекты, скрипты, моделирование, текстурирование, скульптинг
VKонтакте 3Dbuffer

Последнее:

Новый раздел "Текстуры"

Как запатентовать, защитить техническое решение, игру, идею
Форум игроделов » Движки для разработки игр и сложные системы разработки » Unity » Проблема со скриптом
  • Страница 1 из 1
  • 1
Поиск:

Все права сохранены. GcUp.ru © 2008-2024 Рейтинг