forum.boolean.name

forum.boolean.name (http://forum.boolean.name/index.php)
-   Общие вопросы (http://forum.boolean.name/forumdisplay.php?f=166)
-   -   Вопросы от новичка (http://forum.boolean.name/showthread.php?t=15809)

pie 29.12.2012 18:04

Ответ: Вопросы от новичка
 
Всем привет! У меня вопрос по поводу системы Mecanim в Unity3D 4. Делал все вот по этому туториалу:
http://www.youtube.com/watch?v=Xx21y9eJq1U
Вроде бы все нормально. Но вот интересует вопрос как можно реализовать стрейфы (движение в бок)?

pie 29.12.2012 22:21

Ответ: Вопросы от новичка
 
Вроде бы более-менее разобрался. Но возник вопрос. Не удается сделать один переход. Дерево выглядит так:

Переменные:

Переход SideRun -> ForwardRun:


Возникла проблема в том что не могу настроить переход ForwardRun -> SideRun. Кто может подсказать?

Код проигрывания анимации:
Код:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof (Animator))]
[RequireComponent(typeof (CapsuleCollider))]
[RequireComponent(typeof (Rigidbody))]
public class AnimationController : MonoBehaviour {
        public float animSpeed = 1.5f;
        public float lookSmoother = 3f;
        public bool useCurves;

       
        private Animator anim;
        private AnimatorStateInfo currentBaseState;
        private AnimatorStateInfo layer2CurrentState;
        private CapsuleCollider col;
        private float h;
        private float s;
       
        public void Start () {
                anim = GetComponent<Animator>();                                         
                col = GetComponent<CapsuleCollider>();
        }
       
        public void FixedUpdate () {
               
                var A = Input.GetKey(KeyCode.A);
                var D = Input.GetKey(KeyCode.D);
                float target = 0;
               
                if(A != D)
                        target = A?-1:1;
                                                       
                h = Mathf.SmoothDamp(h, target, ref s, 0.1f);
                //float h = Input.GetAxis("Horizontal");
                float v = Input.GetAxis("Vertical");
               
                if (v != 0) {
                        anim.SetFloat("Speed", v);                                                       
                        anim.SetFloat("Direction", h);
                }else{
                        anim.SetFloat("SideSpeed", Mathf.Abs(h));                                                       
                        anim.SetFloat("Direction", h);
                }
                anim.speed = animSpeed;
        }
}


pax 29.12.2012 22:55

Ответ: Вопросы от новичка
 
Кроме как спросить почему логика анимаций в FixedUpdate, а не в Update я ничего не могу сказать. Четвертую Unity некогда смотреть пока.

pie 30.12.2012 22:24

Ответ: Вопросы от новичка
 
Всем привет! Кто работал с CharacterController помогите пожалуйста.
Есть 4 вида анимации движения: вперед, назад, влево, вправо.
Есть скрипты управления:
Код:

using UnityEngine;
using System.Collections;

public class PlatformCharacterController : MonoBehaviour {
       
        private CharacterMotor motor;
       
        public float walkMultiplier = 0.5f;
        public bool defaultIsWalk = false;
       
        // Use this for initialization
        void Start () {
                motor = GetComponent(typeof(CharacterMotor)) as CharacterMotor;
                if (motor==null) Debug.Log("Motor is null!!");
        }
       
        // Update is called once per frame
        void Update () {
                // Get input vector from kayboard or analog stick and make it length 1 at most
                Vector3 directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
                if (directionVector.magnitude > 1) directionVector = directionVector.normalized;
                directionVector = directionVector.normalized * Mathf.Pow(directionVector.magnitude, 2);
               
                // Rotate input vector into camera space so up is camera's up and right is camera's right
                directionVector = Camera.main.transform.rotation * directionVector;
               
                // Rotate input vector to be perpendicular to character's up vector
                Quaternion camToCharacterSpace = Quaternion.FromToRotation(Camera.main.transform.forward*-1, transform.up);
                directionVector = (camToCharacterSpace * directionVector);
               
                // Make input vector relative to Character's own orientation
                directionVector = Quaternion.Inverse(transform.rotation) * directionVector;
               
                if (walkMultiplier != 1) {
                        if ((Input.GetKey("left shift") || Input.GetKey("right shift")) != defaultIsWalk) {
                                directionVector *= walkMultiplier;
                        }
                }
               
                // Apply direction
                motor.desiredMovementDirection = directionVector;
        }
}

Код:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(CharacterController))]
public class NormalCharacterMotor : CharacterMotor {
       
        public float maxRotationSpeed = 270;
       
        private bool firstframe = true;
       
        private void OnEnable () {
                firstframe = true;
        }
       
        private void UpdateFacingDirection() {
                // Calculate which way character should be facing
                float facingWeight = desiredFacingDirection.magnitude;
                Vector3 combinedFacingDirection = (
                        transform.rotation * desiredMovementDirection * (1-facingWeight)
                        + desiredFacingDirection * facingWeight
                );
                combinedFacingDirection = Util.ProjectOntoPlane(combinedFacingDirection, transform.up);
                combinedFacingDirection = alignCorrection * combinedFacingDirection;
               
                if (combinedFacingDirection.sqrMagnitude > 0.01f) {
                        Vector3 newForward = Util.ConstantSlerp(
                                transform.forward,
                                combinedFacingDirection,
                                maxRotationSpeed*Time.deltaTime
                        );
                        newForward = Util.ProjectOntoPlane(newForward, transform.up);
                        //Debug.DrawLine(transform.position, transform.position+newForward, Color.yellow);
                        Quaternion q = new Quaternion();
                        q.SetLookRotation(newForward, transform.up);
                        transform.rotation = q;
                }
        }
       
        private void UpdateVelocity() {
                CharacterController controller = GetComponent(typeof(CharacterController)) as CharacterController;
                Vector3 velocity = controller.velocity;
                if (firstframe) {
                        velocity = Vector3.zero;
                        firstframe = false;
                }
                if (grounded) velocity = Util.ProjectOntoPlane(velocity, transform.up);
               
                // Calculate how fast we should be moving
                Vector3 movement = velocity;
                //bool hasJumped = false;
                jumping = false;
                if (grounded) {
                        // Apply a force that attempts to reach our target velocity
                        Vector3 velocityChange = (desiredVelocity - velocity);
                        if (velocityChange.magnitude > maxVelocityChange) {
                                velocityChange = velocityChange.normalized * maxVelocityChange;
                        }
                        movement += velocityChange;
               
                        // Jump
                        if (canJump && Input.GetButton("Jump")) {
                                movement += transform.up * Mathf.Sqrt(2 * jumpHeight * gravity);
                                //hasJumped = true;
                                jumping = true;
                        }
                }
               
                // Apply downwards gravity
                movement += transform.up * -gravity * Time.deltaTime;
               
                if (jumping) {
                        movement -= transform.up * -gravity * Time.deltaTime / 2;
                }
               
                // Apply movement
                CollisionFlags flags = controller.Move(movement * Time.deltaTime);
                grounded = (flags & CollisionFlags.CollidedBelow) != 0;
        }
       
        // Update is called once per frame
        void Update () {
                UpdateFacingDirection();
               
                UpdateVelocity();
        }
}

Код:

using UnityEngine;
using System.Collections;

public abstract class CharacterMotor : MonoBehaviour {
       
        public float maxForwardSpeed = 1.5f;
        public float maxBackwardsSpeed = 1.5f;
        public float maxSidewaysSpeed = 1.5f;
        public float maxVelocityChange = 0.2f;
       
        public float gravity = 10.0f;
        public bool canJump = true;
        public float jumpHeight = 1.0f;
       
        public Vector3 forwardVector = Vector3.forward;
        protected Quaternion alignCorrection;
       
        private bool m_Grounded = false;
        public bool grounded {
                get { return m_Grounded; }
                protected set { m_Grounded = value; }
        }
       
        private bool m_Jumping = false;
        public bool jumping        {
                get { return m_Jumping; }
                protected set { m_Jumping = value; }
        }
       
        private Vector3 m_desiredMovementDirection;
        private Vector3 m_desiredFacingDirection;
       
        void Start () {
                alignCorrection = new Quaternion();
                alignCorrection.SetLookRotation(forwardVector, Vector3.up);
                alignCorrection = Quaternion.Inverse(alignCorrection);
        }
       
        public Vector3 desiredMovementDirection {
                get { return m_desiredMovementDirection; }
                set {
                        m_desiredMovementDirection = value;
                        if (m_desiredMovementDirection.magnitude>1) m_desiredMovementDirection = m_desiredMovementDirection.normalized;
                }
        }
        public Vector3 desiredFacingDirection {
                get { return m_desiredFacingDirection; }
                set {
                        m_desiredFacingDirection = value;
                        if (m_desiredFacingDirection.magnitude>1) m_desiredFacingDirection = m_desiredFacingDirection.normalized;
                }
        }
        public Vector3 desiredVelocity {
                get {
                        //return m_desiredVelocity;
                        if (m_desiredMovementDirection==Vector3.zero) return Vector3.zero;
                        else {
                                float zAxisEllipseMultiplier = (m_desiredMovementDirection.z>0 ? maxForwardSpeed : maxBackwardsSpeed) / maxSidewaysSpeed;
                                Vector3 temp = new Vector3(m_desiredMovementDirection.x, 0, m_desiredMovementDirection.z/zAxisEllipseMultiplier).normalized;
                                float length = new Vector3(temp.x, 0, temp.z*zAxisEllipseMultiplier).magnitude * maxSidewaysSpeed;
                                Vector3 velocity = m_desiredMovementDirection * length;
                                return transform.rotation * velocity;
                        }
                }
        }
}

Так вот. Как можно сделать чтобы анимации воспроизводились в нужное время. То есть если двигаемся в бок, то воспроизводиться анимация движения в бок и тд. Пытался разобраться в скрипте AngryBots - безуспешно. Спасибо.

Okay 31.12.2012 00:15

Ответ: Вопросы от новичка
 
А не легче свой скрипт написать?

mepihin 31.12.2012 01:15

Ответ: Вопросы от новичка
 
Цитата:

Сообщение от pie (Сообщение 247943)
Так вот. Как можно сделать чтобы анимации воспроизводились в нужное время. То есть если двигаемся в бок, то воспроизводиться анимация движения в бок и тд. Пытался разобраться в скрипте AngryBots - безуспешно. Спасибо.

Смотри, проверь нажатие на клавишу D и A, далее проигрывай анимацию CrossFade, ну если какие-то баги, то проверь на проигрывание другой анимации и отключи проигрование той взамен на новую

pax 31.12.2012 01:36

Ответ: Вопросы от новичка
 
Цитата:

Сообщение от mepihin (Сообщение 247957)
Смотри, проверь нажатие на клавишу D и A, далее проигрывай анимацию CrossFade, ну если какие-то баги, то проверь на проигрывание другой анимации и отключи проигрование той взамен на новую

Тут проблема в том, что игрок при нажатии A может бежать влево на экране, но повернут в эту сторону задом. Почти решили проблему в аське.

WISHMASTER35 31.12.2012 21:30

Ответ: Вопросы от новичка
 
Грубо говоря надо сравнить вектор движения и вектор направления.
Вот так:
Код:

                float dotZ = Vector3.Dot(transform.forward, moveDir);
                float dotX = Vector3.Dot(transform.right, moveDir);
                if( Mathf.Abs(dotZ) > Mathf.Abs(dotX) ) {
                        if(dotZ > 0) PlayRun(shoot);
                        else PlayRunBackward(shoot);
                } else {
                        if(dotX > 0) PlayRunRight(shoot);
                        else PlayRunLeft(shoot);
                }


WISHMASTER35 01.01.2013 00:51

Ответ: Вопросы от новичка
 
Кто-нибудь делал в GUI свои анимации?
Хочу сделать, чтобы при смене меню, старое меню уменьшалось, сдвигалось в сторону и становилось прозрачным. Так кажется на айфонах видел.
Пытался через GUI.matrix сделать, но не получилось. Если менять у матрицы просто масштаб, то не только размеры элементов умножатся на масштаб, но и позиции. Вообщем не понял как масштабировать относительно центра gui элемента или центра нескольких элементов.

pax 01.01.2013 11:30

Ответ: Вопросы от новичка
 
Имхо стандартный GUI для такого не предназначен

is.SarCasm 01.01.2013 18:19

Ответ: Вопросы от новичка
 
Как сделать дополнение к редактору, чтобы было окошко с двумя строчками (высота, ширина) и кнопка "ок". По нажатию создается много кубиков. Как рисовать это меню? Как назначить префаб "куба" ?
P.S. Нет, не майнкрафт

pax 01.01.2013 18:40

Ответ: Вопросы от новичка
 
Расширение редактора (Часть 2)

WISHMASTER35 02.01.2013 03:56

Ответ: Вопросы от новичка
 
Цитата:

Сообщение от pax (Сообщение 248016)
Имхо стандартный GUI для такого не предназначен

Да если бы разобраться с той чертовой матрицей, то можно было бы сделать.

Morganolla 02.01.2013 15:32

Ответ: Вопросы от новичка
 
Как сделать вывод для отладки некоторых переменных в скрипте ( типа float) при проигрывании сцены? Сделать что-то из ГУИ самопальное?

pax 02.01.2013 15:33

Ответ: Вопросы от новичка
 
Имхо да. Есть еще возможность перехватывать лог: http://docs.unity3d.com/Documentatio...gCallback.html


Часовой пояс GMT +4, время: 11:48.

vBulletin® Version 3.6.5.
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Перевод: zCarot