Среда, 29 Мая 2024, 02:48

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

[ Новые сообщения · Игроделы · Правила · Поиск ]
  • Страница 1 из 1
  • 1
Помощь новичку по скриптингу
smmarioДата: Среда, 22 Октября 2014, 10:55 | Сообщение # 1
был не раз
Сейчас нет на сайте
Здравствуйте.
Если кликнуть по объекту и нажать на Q и E объект вращается вокруг своей оси по часовой и против часовой стрелки соответственно на 90 градусов.
А надо, чтобы вращался на 45 градусов.
Если кто поможет буду признателен.
Код

using UnityEngine;
using System.Collections;

public class RaycastHitComparator : IComparer
{
     public int Compare(object x, object y)
     {
      RaycastHit a = (RaycastHit)x;
      RaycastHit b = (RaycastHit)y;
      if(a.distance < b.distance){
       return -1;
      } else if(b.distance < a.distance){
       return 1;
      } else {
       return 0;
      }
     }
}

public class CursorScript : MonoBehaviour {
  int id_ = -1;
  float deck_held_time_ = 0.0f;
  int deck_held_id_ = -1;
  const float DECK_HOLD_THRESHOLD = 0.5f;
  bool card_face_up_ = false;
  int card_rotated_ = 0;
  bool tapping_ = false;
   
  public int id() {
   return id_;
  }
   
  void SetColor(Color color){
   Transform pointer = transform.FindChild("Pointer");
   Transform pointer_tint = pointer.FindChild("pointer_tint");
   Transform default_obj = pointer_tint.FindChild("default");
   default_obj.renderer.material.color = color;  
  }
   
  void Start () {
   if(networkView.isMine){
    id_ = Net.GetMyID();
   }
   if(ObjectManagerScript.Instance()){
    ObjectManagerScript.Instance().RegisterCursorObject(gameObject);
   }
   Screen.showCursor = false;
  }
   
  void OnDestroy() {
   if(ObjectManagerScript.Instance()){
    ObjectManagerScript.Instance().UnRegisterCursorObject(gameObject);
   }
   Screen.showCursor = true;
  }
    
  [RPC]
  public void SetCardFaceUp(bool card_face_up){
   if(Network.isServer && !networkView.isMine){
    networkView.RPC ("SetCardFaceUp",RPCMode.Others, card_face_up);
   } else {
    card_face_up_ = card_face_up;
   }
  }
   
  [RPC]
  public void SetCardRotated(int card_rotated){
   if(Network.isServer && !networkView.isMine){
    networkView.RPC ("SetCardRotated",RPCMode.Others, card_rotated);
   } else {
    card_rotated_ = card_rotated;
   }
  }
   
  public bool tapping() {
   return tapping_;
  }
   
  public int card_rotated() {
   return card_rotated_;
  }
   
  public bool card_face_up() {
   return card_face_up_;
  }
   
  [RPC]
  public void TellObjectManagerAboutGrab(int grab_id, int player_id){
   ObjectManagerScript.Instance().ClientGrab(grab_id, player_id);
  }
   
  [RPC]
  public void TellObjectManagerAboutCardPeel(int grab_id, int player_id){
   ObjectManagerScript.Instance().ClientCardPeel(grab_id, player_id);
  }
   
  [RPC]
  public void TellObjectManagerAboutMouseRelease(int player_id){
   ObjectManagerScript.Instance().ClientReleasedMouse(player_id);
  }
   
  void Grab(int grab_id, int player_id){
   if(!Network.isServer){
    networkView.RPC("TellObjectManagerAboutGrab",RPCMode.Server,grab_id,player_id);
   } else {
    TellObjectManagerAboutGrab(grab_id, player_id);
   }
  }
   
  void Update () {
   var player_list = PlayerListScript.Instance().GetPlayerInfoList();
   if(player_list.ContainsKey(id_)){
    SetColor(player_list[id_].color_);
   }
   if(networkView.isMine){
    if(Input.GetKeyDown("f")){
     card_face_up_ = !card_face_up_;
    }
    if(Input.GetKeyDown("e")){
     card_rotated_ = (card_rotated_+1)%4;
    }
    if(Input.GetKeyDown("q")){
     card_rotated_ = (card_rotated_+3)%4;
    }
    if(Input.GetMouseButtonDown(1)){
     card_face_up_ = false;
     card_rotated_ = 0;
    }
    tapping_ = Input.GetKey ("t");
    var main_camera = GameObject.Find("Main Camera").camera;
    Vector3 pos = new Vector3();
    {
     Ray ray = main_camera.ScreenPointToRay(Input.mousePosition);
     RaycastHit raycast_hit = new RaycastHit();
     if(Physics.Raycast(ray, out raycast_hit, 100.0f, 1 << 8)){
      pos = raycast_hit.point - ray.direction;
     }
    }
     
    if(Input.GetMouseButton(0)){
     Ray ray = main_camera.ScreenPointToRay(Input.mousePosition);
     RaycastHit[] raycast_hits;
     raycast_hits = Physics.RaycastAll(ray);
     System.Array.Sort(raycast_hits, new RaycastHitComparator());
     int hit_deck_id = -1;
     foreach(RaycastHit hit in raycast_hits){  
      var hit_obj = hit.collider.gameObject;
      if(hit_obj.layer != LayerMask.NameToLayer("Dice") &&  
         hit_obj.layer != LayerMask.NameToLayer("Tokens") &&  
         hit_obj.layer != LayerMask.NameToLayer("Cards"))
         {
       continue;
      }
      GrabbableScript grabbable_script = hit_obj.GetComponent<GrabbableScript>();
      if(!grabbable_script){
       hit_obj = hit_obj.transform.parent.gameObject;
       grabbable_script = hit_obj.GetComponent<GrabbableScript>();
      }
      if(hit_obj.GetComponent<DeckScript>()){
       hit_deck_id = grabbable_script.id_;
      }
      if(grabbable_script.held_by_player_ == id_){
       continue;
      }
      if(hit_obj.GetComponent<DeckScript>() && deck_held_time_ > 0.0f && grabbable_script.id_ == deck_held_id_){
       deck_held_time_ += Time.deltaTime;
       if(deck_held_time_ > DECK_HOLD_THRESHOLD){
        Grab(grabbable_script.id_, id_);
       }
       break;
      }
      if(!hit_obj.GetComponent<DiceScript>() && !Input.GetMouseButtonDown(0)){
       continue;
      }
      if(hit_obj.GetComponent<DeckScript>()){
       deck_held_time_ = Time.deltaTime;
       deck_held_id_ = grabbable_script.id_;
       break;
      }      
      Grab(grabbable_script.id_, id_);
     }
     if(hit_deck_id != deck_held_id_ && deck_held_time_ > 0.0f){
      if(!Network.isServer){
       networkView.RPC("TellObjectManagerAboutCardPeel",RPCMode.Server,deck_held_id_,id_);
      } else {
       TellObjectManagerAboutCardPeel(deck_held_id_,id_);
      }
      deck_held_time_ = 0.0f;
     }
    }
    if(Input.GetMouseButtonUp(0)){
     if(!Network.isServer){
      networkView.RPC("TellObjectManagerAboutMouseRelease",RPCMode.Server,id_);
     } else {
      TellObjectManagerAboutMouseRelease(id_);
     }
     deck_held_time_ = 0.0f;
    }
    rigidbody.position = pos;
    transform.position = pos;
   }
  }
   
  void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
  {
   // Send data to server
   if (stream.isWriting)
   {
    int id = id_;
    stream.Serialize(ref id);
    bool tapping = tapping_;
    stream.Serialize(ref tapping);
    bool card_face_up = card_face_up_;
    stream.Serialize(ref card_face_up);
    int card_rotated = card_rotated_;
    stream.Serialize(ref card_rotated);
   }
   // Read data from remote client
   else
   {
    int id = id_;
    stream.Serialize(ref id);
    id_ = id;
    bool tapping = tapping_;
    stream.Serialize(ref tapping);
    tapping_ = tapping;
    bool card_face_up = card_face_up_;
    stream.Serialize(ref card_face_up);
    card_face_up_ = card_face_up;
    int card_rotated = card_rotated_;
    stream.Serialize(ref card_rotated);
    card_rotated_ = card_rotated;
   }
  }
}
MANMANAДата: Среда, 22 Октября 2014, 11:26 | Сообщение # 2
почти ветеран
Сейчас нет на сайте
Вот здесь

Код
    if(Input.GetKeyDown("e")){   
       card_rotated_ = (card_rotated_+1)%4;   
      }   
      if(Input.GetKeyDown("q")){   
       card_rotated_ = (card_rotated_+3)%4;   
      }   


вот так

Код
    if(Input.GetKeyDown("e")){   
       card_rotated_ = (card_rotated_+1)%8;   
      }   
      if(Input.GetKeyDown("q")){   
       card_rotated_ = (card_rotated_+3)%8;   
      }   


"%" позволяет получить остаток от деления (без дробной части).


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

Последнее:

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

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


Сообщение отредактировал MANMANA - Среда, 22 Октября 2014, 11:29
smmarioДата: Среда, 22 Октября 2014, 16:36 | Сообщение # 3
был не раз
Сейчас нет на сайте
Цитата MANMANA ()
Вот здесь

Код
if(Input.GetKeyDown("e")){
card_rotated_ = (card_rotated_+1)%4;
}
if(Input.GetKeyDown("q")){
card_rotated_ = (card_rotated_+3)%4;
}

вот так

Код
if(Input.GetKeyDown("e")){
card_rotated_ = (card_rotated_+1)%8;
}
if(Input.GetKeyDown("q")){
card_rotated_ = (card_rotated_+3)%8;
}

"%" позволяет получить остаток от деления (без дробной части).

Я так уже делал, все равно объект поворачивается на 90 градусов.
Если поставить %2 он поворачивается на 180 градусов.


Сообщение отредактировал smmario - Среда, 22 Октября 2014, 16:53
MANMANAДата: Среда, 22 Октября 2014, 16:46 | Сообщение # 4
почти ветеран
Сейчас нет на сайте
card_rotated - с сервера получаешь?
или в инспекторе выставляется?
вращается он при удерживании кнопки, как я понимаю... мне непонятны вот эти махинации (card_rotated_+1) (card_rotated_+3)...


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

Последнее:

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

Как запатентовать, защитить техническое решение, игру, идею
smmarioДата: Среда, 22 Октября 2014, 19:16 | Сообщение # 5
был не раз
Сейчас нет на сайте
не знаю) я нуб)
были скачаны исходники (Desperate Gods) и благополучно переделывались пока не уткнулся в этот момент.
вращается по единичному нажатию. Если заменить"%" на "*" вращается хаотически
Этот скрипт висит на объекте заменяющем курсор.
там же:
DrawEmptyScript
Код

using UnityEngine;
using System.Collections;

public class DrawEmptyScript : MonoBehaviour {
   void OnDrawGizmos()    {
     Gizmos.color = Color.blue;
     Gizmos.DrawWireSphere(transform.position, 0.1f);
   }
}

NetworkRigidbody
Код

using UnityEngine;
using System.Collections;

public class NetworkRigidbody : MonoBehaviour {
     
   public double m_InterpolationBackTime = 0.1;
   public double m_ExtrapolationLimit = 0.5;
     
   internal struct  State
   {
    internal double timestamp;
    internal Vector3 pos;
    internal Vector3 velocity;
    internal Quaternion rot;
    internal Vector3 angularVelocity;
   }
     
   // We store twenty states with "playback" information
   State[] m_BufferedState = new State[20];
   // Keep track of what slots are used
   int m_TimestampCount;
     
   void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
   {
    // Send data to server
    if (stream.isWriting)
    {
     Vector3 pos = rigidbody.position;
     Quaternion rot = rigidbody.rotation;
     Vector3 velocity = rigidbody.velocity;
     Vector3 angularVelocity = rigidbody.angularVelocity;

     stream.Serialize(ref pos);
     stream.Serialize(ref velocity);
     stream.Serialize(ref rot);
     stream.Serialize(ref angularVelocity);
    }
    // Read data from remote client
    else
    {
     Vector3 pos = Vector3.zero;
     Vector3 velocity = Vector3.zero;
     Quaternion rot = Quaternion.identity;
     Vector3 angularVelocity = Vector3.zero;
     stream.Serialize(ref pos);
     stream.Serialize(ref velocity);
     stream.Serialize(ref rot);
     stream.Serialize(ref angularVelocity);
       
     // Shift the buffer sideways, deleting state 20
     for (int i=m_BufferedState.Length-1;i>=1;i--)
     {
      m_BufferedState[i] = m_BufferedState[i-1];
     }
       
     // Record current state in slot 0
     State state;
     state.timestamp = info.timestamp;
     state.pos = pos;
     state.velocity = velocity;
     state.rot = rot;
     state.angularVelocity = angularVelocity;
     m_BufferedState[0] = state;
       
     // Update used slot count, however never exceed the buffer size
     // Slots aren't actually freed so this just makes sure the buffer is
     // filled up and that uninitalized slots aren't used.
     m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);

     // Check if states are in order, if it is inconsistent you could reshuffel or   
     // drop the out-of-order state. Nothing is done here
     for (int i=0;i<m_TimestampCount-1;i++)
     {
      if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
       Debug.Log("State inconsistent");
     }   
    }
   }
     
   // We have a window of interpolationBackTime where we basically play   
   // By having interpolationBackTime the average ping, you will usually use interpolation.
   // And only if no more data arrives we will use extra polation
   void Update () {
    if(networkView.isMine){
     return;
    }
    rigidbody.isKinematic = true;
    rigidbody.position = m_BufferedState[0].pos;
    rigidbody.rotation = m_BufferedState[0].rot;
    /*if(!networkView.isMine){
     rigidbody.useGravity = false;
    }
      
    // This is the target playback time of the rigid body
    double interpolationTime = Network.time - m_InterpolationBackTime;
      
    // Use interpolation if the target playback time is present in the buffer
    if (m_BufferedState[0].timestamp > interpolationTime)
    {
     // Go through buffer and find correct state to play back
     for (int i=0;i<m_TimestampCount;i++)
     {
      if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
      {
       // The state one slot newer (<100ms) than the best playback state
       State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
       // The best playback state (closest to 100 ms old (default time))
       State lhs = m_BufferedState[i];
         
       // Use the time between the two slots to determine if interpolation is necessary
       double length = rhs.timestamp - lhs.timestamp;
       float t = 0.0F;
       // As the time difference gets closer to 100 ms t gets closer to 1 in   
       // which case rhs is only used
       // Example:
       // Time is 10.000, so sampleTime is 9.900   
       // lhs.time is 9.910 rhs.time is 9.980 length is 0.070
       // t is 9.900 - 9.910 / 0.070 = 0.14. So it uses 14% of rhs, 86% of lhs
       if (length > 0.0001)
        t = (float)((interpolationTime - lhs.timestamp) / length);
         
       // if t=0 => lhs is used directly
       transform.localPosition = Vector3.Lerp(lhs.pos, rhs.pos, t);
       transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
       return;
      }
     }
    }
    // Use extrapolation
    else
    {
     State latest = m_BufferedState[0];
       
     float extrapolationLength = (float)(interpolationTime - latest.timestamp);
     // Don't extrapolation for more than 500 ms, you would need to do that carefully
     if (extrapolationLength < m_ExtrapolationLimit)
     {
      float axisLength = extrapolationLength * latest.angularVelocity.magnitude * Mathf.Rad2Deg;
      Quaternion angularRotation = Quaternion.AngleAxis(axisLength, latest.angularVelocity);
        
      rigidbody.position = latest.pos + latest.velocity * extrapolationLength;
      rigidbody.rotation = angularRotation * latest.rot;
      if(!rigidbody.isKinematic){
       rigidbody.velocity = latest.velocity;
       rigidbody.angularVelocity = latest.angularVelocity;
      }
     }
    }*/
   }
}


Сообщение отредактировал smmario - Среда, 22 Октября 2014, 19:17
berilДата: Среда, 22 Октября 2014, 23:06 | Сообщение # 6
Я не ленивый, я — энергосберегающий
Сейчас нет на сайте
Цитата smmario ()
е знаю) я нуб)

тогда стоит начинать с основ. К примеру движущийся кубик и т.д.




Накодил? Убери за собой!
Инвентарь в Unity(UI)
Инвентарь в Unity(GUI)
MANMANAДата: Среда, 22 Октября 2014, 23:44 | Сообщение # 7
почти ветеран
Сейчас нет на сайте
Цитата smmario ()
не знаю) я нуб)

я бы не стал влезать в 700-метровый проект smile
лично в моем случае (5 мин назад) "veni, vedi, vici" для данного проекта переводилось как: скачал, посмотрел, удалил.


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

Последнее:

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

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


Сообщение отредактировал MANMANA - Среда, 22 Октября 2014, 23:45
smmarioДата: Четверг, 23 Октября 2014, 15:32 | Сообщение # 8
был не раз
Сейчас нет на сайте
Цитата MANMANA ()
я бы не стал влезать в 700-метровый проект


Но я влез) и вот что получилось:


Кому интересно: https://yadi.sk/d/RVkYqo6-buV8q
Только запускайте в окне (если свернуть игру в полноэкранном режиме она не разворачивается обратно)
И не работает на x86 системах

Сейчас делаю другой проект, но там надо, что бы объекты вращались на 45 градусов.

Добавлено (23.10.2014, 15:32)
---------------------------------------------
Нашел решение проблемы, спасибо MANMANA, вы направили в правильную сторону.

Сообщение отредактировал smmario - Четверг, 23 Октября 2014, 08:33
DalyДата: Четверг, 23 Октября 2014, 15:32 | Сообщение # 9
постоянный участник
Сейчас нет на сайте
smmario,

Код
Vector3 rot;

    if(Input.GetKeyDown(KeyCode.Q))
    {
     rot -= new Vector3(0,[b]90[/b],0);
     объект.transform.rotation = Quaternion.AngleAxis(rot.magnitude,rot);
    }


Сообщение отредактировал Daly - Четверг, 23 Октября 2014, 15:32
MANMANAДата: Четверг, 23 Октября 2014, 16:31 | Сообщение # 10
почти ветеран
Сейчас нет на сайте
smmario, выложи решение проблемы то.
Мне например, интересно. smile
А решение от Daly ? подходит?


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

Последнее:

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

Как запатентовать, защитить техническое решение, игру, идею
DalyДата: Четверг, 23 Октября 2014, 16:51 | Сообщение # 11
постоянный участник
Сейчас нет на сайте
MANMANA, А почему бы и нет? Создается локальная точка, и относительно нее задаем вращение.
MANMANAДата: Четверг, 23 Октября 2014, 17:03 | Сообщение # 12
почти ветеран
Сейчас нет на сайте
таки не совсем понятно, что творится с "card_rotated_" и "card_rotated", там и int card_rotated () есть...

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

Последнее:

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

Как запатентовать, защитить техническое решение, игру, идею
smmarioДата: Воскресенье, 26 Октября 2014, 14:55 | Сообщение # 13
был не раз
Сейчас нет на сайте
Цитата MANMANA ()
smmario, выложи решение проблемы то.


Вот тут:
Код

if(grabbable.GetComponent<ParentTokenScript>()){
      target_rotation = Quaternion.AngleAxis(cursor_script.card_rotated() * 45, new Vector3(0,1,0)) * target_rotation;
     }


Скрипт полностью:
ObjectManagerScript
Код

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ObjectManagerScript : MonoBehaviour {   
   public GameObject deck_prefab;
   List<GameObject> grabbable_objects = new List<GameObject>();   
   List<GameObject> cursor_objects = new List<GameObject>();
   GameObject board_object = null;
   const float HOLD_FORCE = 20000.0f;
   const float ANGULAR_FORCE = 400.0f;
   const float HOLD_LINEAR_DAMPENING = 0.4f;
   const float HOLD_ANGULAR_DAMPENING = 0.4f;
   const float MAX_DICE_VEL = 15.0f;
   const float DICE_ANG_SPEED = 300.0f;
   const float DECK_MERGE_THRESHOLD = 0.4f;
   const float SHAKE_THRESHOLD = 1.0f;
   int free_id = 0;
     
   public void RegisterBoardObject(GameObject obj){
    board_object = obj;
   }
     
   public void UnRegisterBoardObject(){
    board_object = null;
   }
     
   int GetRotateFromGrabbable(GameObject grabbable){
    var forward = grabbable.transform.forward;
    if(!grabbable.GetComponent<DeckScript>()){
     forward *= -1.0f;
    }
    float ang = Mathf.Atan2(forward.z, -forward.x)*180.0f/Mathf.PI;
    int rotate = -1;
    if(ang >=-45.0f && ang < 45.0f){
     rotate = 1;
    } else if(ang >= 45.0f && ang < 135.0f){
     rotate = 2;
    } else if(ang >= -135.0f && ang < -45.0f){
     rotate = 0;
    } else {
     rotate = 3;
    }
    return rotate;
   }
     
   public void ClientGrab(int grabbed_id, int player_id){
    // Check if client is already holding dice or tokens
    bool holding_anything = false;
    bool holding_anything_but_dice = false;
    foreach(GameObject grabbable in grabbable_objects){
     GrabbableScript grabbable_script = grabbable.GetComponent<GrabbableScript>();
     if(grabbable_script.held_by_player_ == player_id){
      holding_anything = true;
      if(!grabbable.GetComponent<DiceScript>()){
       holding_anything_but_dice = true;
      }
     }
    }
    CursorScript cursor_script = null;
    foreach(GameObject cursor in cursor_objects){
     if(cursor.GetComponent<CursorScript>().id() == player_id){
      cursor_script = cursor.GetComponent<CursorScript>();
     }
    }
    // See if client can grab object given already-grabbed objects
    foreach(GameObject grabbable in grabbable_objects){
     GrabbableScript grabbable_script = grabbable.GetComponent<GrabbableScript>();
     if(grabbable_script.id_ == grabbed_id){
      if(grabbable_script.held_by_player_ == player_id){
       return;
      }
      if((grabbable.GetComponent<DiceScript>() && !holding_anything_but_dice) ||
         (grabbable.GetComponent<TokenScript>() && !holding_anything)||
         (grabbable.GetComponent<ParentTokenScript>() && !holding_anything)||
         (grabbable.GetComponent<DeckScript>() && !holding_anything) ||
            (grabbable.GetComponent<CardScript>() && !holding_anything)||
            (grabbable.GetComponent<CoinScript>() && !holding_anything))
         {
       grabbable_script.held_by_player_ = player_id;
       if(grabbable.GetComponent<DiceScript>()){
        grabbable.GetComponent<DiceScript>().PickUpSound();
       }
       if(grabbable.GetComponent<CoinScript>()){
        grabbable.GetComponent<CoinScript>().PickUpSound();
       }
       if(grabbable.GetComponent<DeckScript>()){
        cursor_script.SetCardFaceUp((grabbable.transform.up.y > 0.0f));
        cursor_script.SetCardRotated(GetRotateFromGrabbable(grabbable));
        grabbable.GetComponent<DeckScript>().PickUpSound();
       }
       if(grabbable.GetComponent<CardScript>()){
        cursor_script.SetCardFaceUp((grabbable.transform.up.y < 0.0f));
        cursor_script.SetCardRotated(GetRotateFromGrabbable(grabbable));
        grabbable.GetComponent<CardScript>().PickUpSound();
       }
       if(grabbable.GetComponent<TokenScript>()){
        grabbable.GetComponent<TokenScript>().PickUpSound();
       }
       if(grabbable.GetComponent<ParentTokenScript>()){
        grabbable.GetComponent<ParentTokenScript>().PickUpSound();
        cursor_script.SetCardRotated(GetRotateFromGrabbable(grabbable));
       }
       grabbable.rigidbody.mass = 0.2f;
      }
     }
    }
   }
     
     
   public void ClientCardPeel(int grabbed_id, int player_id){
    // Return if player is already holding something
    foreach(GameObject grabbable in grabbable_objects){
     if(grabbable.GetComponent<GrabbableScript>().held_by_player_ == player_id){
         return;
        }
    }
    // Find the deck, return if can't find it
    GameObject deck = null;
    foreach(GameObject grabbable in grabbable_objects){
     if(grabbable.GetComponent<GrabbableScript>().id_ == grabbed_id &&
        grabbable.GetComponent<DeckScript>())
        {
         deck = grabbable;
        }
    }
    if(!deck){
     return;
    }
    // Grab whatever card is on top of the deck, depending on which way
    // the deck is facing
    GameObject card = null;
    if((deck.rigidbody.rotation * new Vector3(0,1,0)).y >= 0.0f){
     card = deck.GetComponent<DeckScript>().TakeCard(true);
    } else {
     card = deck.GetComponent<DeckScript>().TakeCard(false);
    }
    card.GetComponent<GrabbableScript>().held_by_player_ = player_id;
    CursorScript cursor_script = null;
    foreach(GameObject cursor in cursor_objects){
     if(cursor.GetComponent<CursorScript>().id() == player_id){
      cursor_script = cursor.GetComponent<CursorScript>();
     }
    }
    cursor_script.SetCardFaceUp((card.transform.up.y < 0.0f));
    cursor_script.SetCardRotated(GetRotateFromGrabbable(card));
    card.GetComponent<CardScript>().PickUpSound();
   }
     
   public GameObject GetMyCursorObject() {
    foreach(var cursor in cursor_objects){
     if(cursor.GetComponent<CursorScript>().id() == Net.GetMyID()){   
      return cursor;
     }
    }
    return null;
   }
     
   public void ClientReleasedMouse(int player_id){
    foreach(GameObject grabbable in grabbable_objects){
     var grabbable_script = grabbable.GetComponent<GrabbableScript>();
     if(grabbable_script.held_by_player_ == player_id){
      grabbable.rigidbody.velocity = new Vector3(grabbable.rigidbody.velocity.x, -5.0f, grabbable.rigidbody.velocity.z);
      if(grabbable.rigidbody.velocity.magnitude > MAX_DICE_VEL){
       grabbable.rigidbody.velocity = grabbable.rigidbody.velocity.normalized * MAX_DICE_VEL;
      }
      if(grabbable.GetComponent<DiceScript>()){
       grabbable.rigidbody.angularVelocity = new Vector3(Random.Range(-1.0f,1.0f),Random.Range(-1.0f,1.0f),Random.Range(-1.0f,1.0f)) * DICE_ANG_SPEED;     
      }
      grabbable.rigidbody.mass = 1.0f;
      grabbable_script.held_by_player_ = -1;
     }
    }
   }
     
   public void RegisterCursorObject(GameObject obj) {
    cursor_objects.Add(obj);
   }
     
   public void UnRegisterCursorObject(GameObject obj) {
    cursor_objects.Remove(obj);
   }
     
   public void RegisterGrabbableObject(GameObject obj) {
    grabbable_objects.Add(obj);
    obj.GetComponent<GrabbableScript>().id_ = free_id;
    ++free_id;
   }
     
   public void UnRegisterGrabbableObject(GameObject obj) {
    grabbable_objects.Remove(obj);
   }
     
   [RPC]
   void DestroyObject(NetworkViewID id){
    GameObject.Destroy(NetworkView.Find(id).gameObject);
   }
     
   [RPC]
   public void RecoverDice() {
    if(!Network.isServer){
     networkView.RPC("RecoverDice", RPCMode.Server);
     return;
    } else {
     foreach(GameObject grabbable in grabbable_objects){
      networkView.RPC("DestroyObject",RPCMode.AllBuffered,grabbable.networkView.viewID);
     }
     board_object.GetComponent<BoardScript>().SpawnDice();
     NetUIScript.Instance().SpawnHealthTokens();
    }
   }
     
   void AssignTokenColors() {
    // Create list of tokens
    var token_objects = new List<GameObject>();
    foreach(GameObject grabbable in grabbable_objects){
     if(grabbable.GetComponent<TokenScript>()){
      token_objects.Add(grabbable);
     }
    }
    var players = PlayerListScript.Instance().GetPlayerInfoList();
    // Assign owners to tokens as needed
    if(Network.isServer){
     var used_id = new HashSet<int>();
     foreach(GameObject token in token_objects){
      used_id.Add(token.GetComponent<TokenScript>().owner_id_);
     }
     foreach(GameObject token in token_objects){
      var token_script = token.GetComponent<TokenScript>();
      if(!players.ContainsKey(token_script.owner_id_)){
       foreach(var pair in players){
        if(!used_id.Contains(pair.Key)){
         token_script.owner_id_ = pair.Key;
         used_id.Add(pair.Key);
        }
       }
      }
     }
    }
    // Assign colors to tokens based on owner
    foreach(GameObject token in token_objects){
     var token_script = token.GetComponent<TokenScript>();
     if(players.ContainsKey(token_script.owner_id_)){
      token.renderer.material.color = players[token_script.owner_id_].color_;
     } else {
      token.renderer.material.color = Color.white;
     }
    }
   }
     
   void Update () {
   }
     
   void UpdatePhysicsState(GameObject grabbable, GameObject holder){
    var held_rigidbody = grabbable.rigidbody;
    var target_position = holder.transform.position;
    var cursor_script = holder.GetComponent<CursorScript>();
    if(!cursor_script.tapping()){
     target_position.y += 0.5f;
    } else {
     target_position.y -= 1.3f;
    }
    if(grabbable.GetComponent<DeckScript>() || grabbable.GetComponent<CardScript>() || grabbable.GetComponent<ParentTokenScript>()){
     target_position.y += 0.5f;
     Quaternion target_rotation = Quaternion.identity;
     if(grabbable.GetComponent<DeckScript>() || grabbable.GetComponent<CardScript>()){
      if(grabbable.GetComponent<DeckScript>()){
       target_rotation = Quaternion.AngleAxis(180,new Vector3(0,1,0)) * target_rotation;
       target_rotation = Quaternion.AngleAxis(180,new Vector3(0,0,1)) * target_rotation;
      }
      if(cursor_script.card_face_up()){
       target_rotation = Quaternion.AngleAxis(180,new Vector3(0,0,1))*target_rotation;
      }
      target_rotation = Quaternion.AngleAxis(cursor_script.card_rotated() * 90, new Vector3(0,1,0)) * target_rotation;
     }
     if(grabbable.GetComponent<ParentTokenScript>()){
      target_rotation = Quaternion.AngleAxis(cursor_script.card_rotated() * 45, new Vector3(0,1,0)) * target_rotation;
     }
     Quaternion offset = target_rotation * Quaternion.Inverse(held_rigidbody.rotation);
     float angle;
     Vector3 offset_vec3;
     offset.ToAngleAxis(out angle, out offset_vec3);
     if(angle > 180){
      angle -= 360;
     }
     if(angle < -180){
      angle += 360;
     }
     if(angle != 0.0f){
      offset_vec3 *= angle;
      float mult = 1.0f;
      if(grabbable.GetComponent<ParentTokenScript>()){
       mult = 0.1f;
      }
      held_rigidbody.AddTorque(offset_vec3 * Time.deltaTime * ANGULAR_FORCE * mult * held_rigidbody.mass);
     }
    }
    if(!cursor_script.tapping() && Vector3.Dot(target_position - held_rigidbody.position, held_rigidbody.velocity) < -SHAKE_THRESHOLD){
     //ConsoleScript.Log("Shake");
     if(grabbable.GetComponent<DiceScript>()){
      for(int i=0; i<10; ++i){
       held_rigidbody.rotation = Quaternion.AngleAxis(Random.Range(0.0f,360.0f),new Vector3(Random.Range(-1.0f,1.0f),Random.Range(-1.0f,1.0f),Random.Range(-1.0f,1.0f)).normalized) * held_rigidbody.rotation;
      }
      grabbable.GetComponent<DiceScript>().ShakeSound();
     }
     if(grabbable.GetComponent<DeckScript>()){
      grabbable.GetComponent<DeckScript>().Shuffle();
     }
    }
    held_rigidbody.AddForce((target_position - held_rigidbody.position) * Time.deltaTime * HOLD_FORCE * held_rigidbody.mass);
    held_rigidbody.velocity *= HOLD_LINEAR_DAMPENING;     
    held_rigidbody.angularVelocity *= HOLD_ANGULAR_DAMPENING;   
    held_rigidbody.WakeUp();
   }
     
   void FixedUpdate() {
    if(Network.isServer){
     // Move grabbed objects to position of cursor
     foreach(GameObject grabbable in grabbable_objects){
      int held_by_player = grabbable.GetComponent<GrabbableScript>().held_by_player_;
      if(held_by_player != -1){
       GameObject holder = null;
       foreach(GameObject cursor in cursor_objects){
        if(cursor.GetComponent<CursorScript>().id() == held_by_player){
         holder = cursor;
        }
       }
       if(holder){
        UpdatePhysicsState(grabbable, holder);
       } else {
        ConsoleScript.Log("Could not find cursor for player: "+held_by_player);
       }
      }
     }
    }
   }
     
   public static ObjectManagerScript Instance() {
    if(!GameObject.Find("GlobalScriptObject")){
     return null;
    }
    return GameObject.Find("GlobalScriptObject").GetComponent<ObjectManagerScript>();
   }
     
   public void NotifyCardHitDeck(GameObject card, GameObject deck){
    if(card.GetComponent<CardScript>().card_id() == -1 ||
       deck.GetComponent<DeckScript>().GetCards().Count < 1)
       {
     return;
    }
    bool facing_same_way = Vector3.Dot(card.transform.up, deck.transform.up) <= 0.0;
    var rel_pos = card.transform.position - deck.transform.position;
    bool close_enough = false;
    if(Mathf.Abs(Vector3.Dot(rel_pos, deck.transform.forward)) < DECK_MERGE_THRESHOLD &&   
       Mathf.Abs(Vector3.Dot(rel_pos, deck.transform.right)) < DECK_MERGE_THRESHOLD &&
       Mathf.Abs(Vector3.Dot(card.transform.forward, deck.transform.forward)) > 0.5f)
       {
     close_enough = true;
    }
    if(card.GetComponent<GrabbableScript>().held_by_player_ == -1 && facing_same_way && close_enough){
     bool top = Vector3.Dot(card.transform.position - deck.transform.position, deck.transform.up) >= 0.0;
     deck.GetComponent<DeckScript>().AddCard(top, card.GetComponent<CardScript>().card_id());
     card.GetComponent<CardScript>().SetCardID(-1);
     networkView.RPC("DestroyObject",RPCMode.AllBuffered,card.networkView.viewID);
    }
   }
     
     
   public void NotifyDeckHitDeck(GameObject deck_a, GameObject deck_b){
    if(deck_b.GetComponent<DeckScript>().GetCards().Count == 0 ||
       deck_a.GetComponent<DeckScript>().GetCards().Count == 0)
       {
      return;    
    }
    bool facing_same_way = Vector3.Dot(deck_a.transform.up, deck_b.transform.up) > 0.0;
    var rel_pos = deck_a.transform.position - deck_b.transform.position;
    bool close_enough = false;
    if(Mathf.Abs(Vector3.Dot(rel_pos, deck_a.transform.forward)) < DECK_MERGE_THRESHOLD &&   
       Mathf.Abs(Vector3.Dot(rel_pos, deck_a.transform.right)) < DECK_MERGE_THRESHOLD &&
       Mathf.Abs(Vector3.Dot(rel_pos, deck_b.transform.forward)) < DECK_MERGE_THRESHOLD &&   
       Mathf.Abs(Vector3.Dot(rel_pos, deck_b.transform.right)) < DECK_MERGE_THRESHOLD &&
       Mathf.Abs(Vector3.Dot(deck_a.transform.forward, deck_b.transform.forward)) > 0.5f)
       {
     close_enough = true;
    }
    if(deck_a.GetComponent<GrabbableScript>().held_by_player_ == -1 && deck_b.GetComponent<GrabbableScript>().held_by_player_ == -1 && facing_same_way && close_enough){
     bool top = Vector3.Dot(deck_a.transform.position - deck_b.transform.position, deck_a.transform.up) <= 0.0;
     var cards = deck_b.GetComponent<DeckScript>().GetCards();
     if(!top){
      foreach(var card in cards){
       deck_a.GetComponent<DeckScript>().AddCard(top, card);
      }
     } else {
      for(int i=cards.Count-1; i>=0; --i){
       deck_a.GetComponent<DeckScript>().AddCard(top, cards[i]);
      }
     }
     cards.Clear();
     networkView.RPC("DestroyObject",RPCMode.AllBuffered,deck_b.networkView.viewID);
    }
   }
     
   public void NotifyCardHitCard(GameObject card_a, GameObject card_b){
    if(card_a.GetComponent<CardScript>().card_id() == -1 ||
       card_b.GetComponent<CardScript>().card_id() == -1){
     return;
    }
    bool facing_same_way = Vector3.Dot(card_a.transform.up, card_b.transform.up) > 0.0;
    var rel_pos = card_a.transform.position - card_b.transform.position;
    bool close_enough = false;
    if(Mathf.Abs(Vector3.Dot(rel_pos, card_b.transform.forward)) < DECK_MERGE_THRESHOLD &&   
       Mathf.Abs(Vector3.Dot(rel_pos, card_b.transform.right)) < DECK_MERGE_THRESHOLD &&
       Mathf.Abs(Vector3.Dot(rel_pos, card_a.transform.forward)) < DECK_MERGE_THRESHOLD &&   
       Mathf.Abs(Vector3.Dot(rel_pos, card_a.transform.right)) < DECK_MERGE_THRESHOLD &&
       Mathf.Abs(Vector3.Dot(card_a.transform.forward, card_b.transform.forward)) > 0.5f)
       {
     close_enough = true;
    }
    if(card_a.GetComponent<GrabbableScript>().held_by_player_ == -1 && card_b.GetComponent<GrabbableScript>().held_by_player_ == -1 && facing_same_way && close_enough){
     bool top = Vector3.Dot(card_a.transform.position - card_b.transform.position, card_a.transform.up) >= 0.0;
     var deck = (GameObject)Network.Instantiate(deck_prefab, (card_a.transform.position + card_b.transform.position)*0.5f, card_a.transform.rotation,0);   
     deck.transform.rotation = Quaternion.AngleAxis(180,deck.transform.right)*deck.transform.rotation;
     deck.GetComponent<DeckScript>().AddCard(top, card_a.GetComponent<CardScript>().card_id());
     deck.GetComponent<DeckScript>().AddCard(top, card_b.GetComponent<CardScript>().card_id());
     card_a.GetComponent<CardScript>().SetCardID(-1);
     networkView.RPC("DestroyObject",RPCMode.AllBuffered,card_a.networkView.viewID);
     card_b.GetComponent<CardScript>().SetCardID(-1);
     networkView.RPC("DestroyObject",RPCMode.AllBuffered,card_b.networkView.viewID);
    }
   }
}


Правда появилась другая проблема:
поскольку объект теперь ориентируется не на 4 стороны, а на 8, объект при клике мышке сначала поворачивается ориентируясь в какую либо сторону, а уже потом поворачивается по нажатию клавиш.

Есть подозрения, что решение должно быть здесь:
Код

float ang = Mathf.Atan2(forward.z, -forward.x)*180.0f/Mathf.PI;
    int rotate = -1;
    if(ang >=-45.0f && ang < 45.0f){
     rotate = 1;
    } else if(ang >= 45.0f && ang < 135.0f){
     rotate = 2;
    } else if(ang >= -135.0f && ang < -45.0f){
     rotate = 0;
    } else {
     rotate = 3;
    }
    return rotate;

Добавлено (26.10.2014, 13:54)
---------------------------------------------
В общем вот

Код

float ang = Mathf.Atan2(forward.z, -forward.x)*180.0f/Mathf.PI;
   int rotate = -1;
   if(ang >= -22.5f && ang < 22.5f){
    rotate = 2;
   } else if(ang >= 67.5f && ang < 112.5f){
    rotate = 4;
   } else if(ang >= -112.5f && ang < -67.5f){
    rotate = 0;
   } else if(ang >= -67.5f && ang < -22.5f){
    rotate = 1;
   } else if(ang >= 22.5f && ang < 67.5f){
    rotate = 3;
   } else if(ang >= 112.5f && ang < 157.5f){
    rotate = 5;
   } else if(ang >= -157.5f && ang < 157.5f){
    rotate = 7;
   } else {
    rotate = 6;
   }
   return rotate;
  }

Добавлено (26.10.2014, 14:55)
---------------------------------------------
Подскажите как исправить эту часть кода:

Код

if(Input.GetMouseButtonDown(1)){
     card_face_up_ = !card_face_up_;
    }
    if(Input.GetKeyDown("e")){
     card_rotated_ = (card_rotated_+1)%8;
    }
    if(Input.GetKeyDown("q")){
     card_rotated_ = (card_rotated_-1)%8;
    }
    if(Input.GetKeyDown("r")){
     card_face_up_ = false;
     card_rotated_ = 0;
    }
    if(Input.GetKeyDown("f")){
     card_rotated_ = (card_rotated_+ )%8;
    }
    tapping_ = Input.GetKey ("t");
    var main_camera = GameObject.Find("Main Camera").camera;
    Vector3 pos = new Vector3();

что бы при нажатии на эту кнопку "F" объект вращался на рандомное значение ( от 1 до 8 )и желательно повернулся несколько раз


Сообщение отредактировал smmario - Суббота, 25 Октября 2014, 15:51
MANMANAДата: Воскресенье, 26 Октября 2014, 16:03 | Сообщение # 14
почти ветеран
Сейчас нет на сайте
Random.Range (1.0f, 8.0f);

только вот это card_rotated_ = (card_rotated_+ )%8; - очень странная строка. Unity ничего не пишет тебе по этому поводу? smile
а куда поставить рандом - тебе решать.
поворот сделать лерпом?


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

Последнее:

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

Как запатентовать, защитить техническое решение, игру, идею
smmarioДата: Воскресенье, 26 Октября 2014, 16:49 | Сообщение # 15
был не раз
Сейчас нет на сайте
Уже сделал так:
Код

if(Input.GetKeyDown("f")){
card_rotated_ = Random.Range(1,8)*2;

Правда я хотел сделать чтобы он поворачивался несколько раз, но это не критично.
  • Страница 1 из 1
  • 1
Поиск:

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