Форум программистов, компьютерный форум, киберфорум
Unity, Unity3D
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.90/10: Рейтинг темы: голосов - 10, средняя оценка - 4.90
0 / 0 / 0
Регистрация: 14.03.2021
Сообщений: 23

Небольшая Проблема с осями

22.03.2021, 20:12. Показов 2241. Ответов 6

Студворк — интернет-сервис помощи студентам
Добрый вечер. Делаю управление для Rigidbody по туториалу:
Каким образом здесь задаются оси, как и тд.?(А то не совсем понимаю)

Добавлено через 34 минуты
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.03.2021, 20:12
Ответы с готовыми решениями:

Сделать загрузочную флешку с осями (инсталяторами) и загрузочными осями нужными прогами
Народ подскажите как можно сделать загрузочную флешку с осями (инстоляторами) и загрузочными осями + Нужными прогами. А то через YUMI...

Небольшая проблема
Я делала задачу №692 на сайте ******** "Бинарные числа" Говорят, что плохой программист – это тот, кто считает, что в одном...

Небольшая проблема с файлом
import sys from random import choice from PyQt5.QtWidgets import QLineEdit, QPushButton, QApplication from PyQt5.QtWidgets import...

6
35 / 26 / 11
Регистрация: 30.01.2018
Сообщений: 169
22.03.2021, 21:24
Нам все 10 мин смотреть) ?
0
0 / 0 / 0
Регистрация: 14.03.2021
Сообщений: 23
22.03.2021, 21:54  [ТС]
Цитата Сообщение от Srgey1232 Посмотреть сообщение
Нам все 10 мин смотреть) ?
возможно

Добавлено через 23 секунды
Цитата Сообщение от Srgey1232 Посмотреть сообщение
Нам все 10 мин смотреть) ?
Могу итоговый скрипт вывести
0
2 / 1 / 1
Регистрация: 23.03.2021
Сообщений: 17
23.03.2021, 21:23
выведи скрипт !!
0
0 / 0 / 0
Регистрация: 14.03.2021
Сообщений: 23
24.03.2021, 09:41  [ТС]
Цитата Сообщение от ХоббиТок Посмотреть сообщение
выведи скрипт !!
скрипт
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
 
namespace UnityStandardAssets.Characters.FirstPerson
{
    [RequireComponent(typeof (Rigidbody))]
    [RequireComponent(typeof (CapsuleCollider))]
    public class RigidbodyFirstPersonController : MonoBehaviour
    {
        [Serializable]
        public class MovementSettings
        {
            public float ForwardSpeed = 8.0f;   // Speed when walking forward
            public float BackwardSpeed = 4.0f;  // Speed when walking backwards
            public float StrafeSpeed = 4.0f;    // Speed when walking sideways
            public float RunMultiplier = 2.0f;   // Speed when sprinting
            public KeyCode RunKey = KeyCode.LeftShift;
            public float JumpForce = 30f;
            public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
            [HideInInspector] public float CurrentTargetSpeed = 8f;
 
#if !MOBILE_INPUT
            private bool m_Running;
#endif
 
            public void UpdateDesiredTargetSpeed(Vector2 input)
            {
                if (input == Vector2.zero) return;
                if (input.x > 0 || input.x < 0)
                {
                    //strafe
                    CurrentTargetSpeed = StrafeSpeed;
                }
                if (input.y < 0)
                {
                    //backwards
                    CurrentTargetSpeed = BackwardSpeed;
                }
                if (input.y > 0)
                {
                    //forwards
                    //handled last as if strafing and moving forward at the same time forwards speed should take precedence
                    CurrentTargetSpeed = ForwardSpeed;
                }
#if !MOBILE_INPUT
                if (Input.GetKey(RunKey))
                {
                    CurrentTargetSpeed *= RunMultiplier;
                    m_Running = true;
                }
                else
                {
                    m_Running = false;
                }
#endif
            }
 
#if !MOBILE_INPUT
            public bool Running
            {
                get { return m_Running; }
            }
#endif
        }
 
 
        [Serializable]
        public class AdvancedSettings
        {
            public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
            public float stickToGroundHelperDistance = 0.5f; // stops the character
            public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
            public bool airControl; // can the user control the direction that is being moved in the air
            [Tooltip("set it to 0.1 or more if you get stuck in wall")]
            public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
        }
 
 
        public Camera cam;
        public MovementSettings movementSettings = new MovementSettings();
        public MouseLook mouseLook = new MouseLook();
        public AdvancedSettings advancedSettings = new AdvancedSettings();
 
 
        private Rigidbody m_RigidBody;
        private CapsuleCollider m_Capsule;
        private float m_YRotation;
        private Vector3 m_GroundContactNormal;
        private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
 
        [HideInInspector]
        public Vector2 RunAxis;
        [HideInInspector]
        public bool JumpAxis;
 
 
        public Vector3 Velocity
        {
            get { return m_RigidBody.velocity; }
        }
 
        public bool Grounded
        {
            get { return m_IsGrounded; }
        }
 
        public bool Jumping
        {
            get { return m_Jumping; }
        }
 
        public bool Running
        {
            get
            {
 #if !MOBILE_INPUT
                return movementSettings.Running;
#else
                return false;
#endif
            }
        }
 
 
        private void Start()
        {
            m_RigidBody = GetComponent<Rigidbody>();
            m_Capsule = GetComponent<CapsuleCollider>();
            mouseLook.Init (transform, cam.transform);
        }
 
 
        private void Update()
        {
            RotateView();
 
            if (JumpAxis && !m_Jump)
            {
                m_Jump = true;
            }
        }
 
 
        private void FixedUpdate()
        {
            GroundCheck();
            Vector2 input = GetInput();
 
            if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
            {
                // always move along the camera forward as it is the direction that it being aimed at
                Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
                desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
 
                desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
                desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
                desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
                if (m_RigidBody.velocity.sqrMagnitude <
                    (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
                {
                    m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
                }
            }
 
            if (m_IsGrounded)
            {
                m_RigidBody.drag = 5f;
 
                if (m_Jump)
                {
                    m_RigidBody.drag = 0f;
                    m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
                    m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
                    m_Jumping = true;
                }
 
                if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
                {
                    m_RigidBody.Sleep();
                }
            }
            else
            {
                m_RigidBody.drag = 0f;
                if (m_PreviouslyGrounded && !m_Jumping)
                {
                    StickToGroundHelper();
                }
            }
            m_Jump = false;
        }
 
 
        private float SlopeMultiplier()
        {
            float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
            return movementSettings.SlopeCurveModifier.Evaluate(angle);
        }
 
 
        private void StickToGroundHelper()
        {
            RaycastHit hitInfo;
            if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                   ((m_Capsule.height/2f) - m_Capsule.radius) +
                                   advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
            {
                if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
                {
                    m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
                }
            }
        }
 
 
        private Vector2 GetInput()
        {
            
            Vector2 input = new Vector2
                {
                    x = RunAxis.x,
                    y = RunAxis.y
                };
            movementSettings.UpdateDesiredTargetSpeed(input);
            return input;
        }
 
 
        private void RotateView()
        {
            //avoids the mouse looking if the game is effectively paused
            if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
 
            // get the rotation before it's changed
            float oldYRotation = transform.eulerAngles.y;
 
            mouseLook.LookRotation (transform, cam.transform);
 
            if (m_IsGrounded || advancedSettings.airControl)
            {
                // Rotate the rigidbody velocity to match the new direction that the character is looking
                Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
                m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
            }
        }
 
        /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
        private void GroundCheck()
        {
            m_PreviouslyGrounded = m_IsGrounded;
            RaycastHit hitInfo;
            if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                   ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
            {
                m_IsGrounded = true;
                m_GroundContactNormal = hitInfo.normal;
            }
            else
            {
                m_IsGrounded = false;
                m_GroundContactNormal = Vector3.up;
            }
            if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
            {
                m_Jumping = false;
            }
        }
    }
}
0
35 / 26 / 11
Регистрация: 30.01.2018
Сообщений: 169
24.03.2021, 13:10
Лучший ответ Сообщение было отмечено Apelsin4k как решение

Решение

Да просить код было неудачной идеей) Я быстро просмотрел видос.. в общем ничего нового, объясню математическую модель.
Он просто проецирует систему координат джойстика на систему координат игрока(gameobject которым управляет джойстик). То есть ось абсцисс джойстика изменяет ось z у игрока. А вот с осью ординат немного по другому, тут связываются оси : ординат у джойстика и ось абсцисс у игрока , так как игрок находится в 3д пространстве.
Миниатюры
Небольшая Проблема с осями  
0
0 / 0 / 0
Регистрация: 14.03.2021
Сообщений: 23
24.03.2021, 17:41  [ТС]
Цитата Сообщение от Srgey1232 Посмотреть сообщение
Да просить код было неудачной идеей) Я быстро просмотрел видос.. в общем ничего нового, объясню математическую модель.
Он просто проецирует систему координат джойстика на систему координат игрока(gameobject которым управляет джойстик). То есть ось абсцисс джойстика изменяет ось z у игрока. А вот с осью ординат немного по другому, тут связываются оси : ординат у джойстика и ось абсцисс у игрока , так как игрок находится в 3д пространстве.
Спасибо за ответ. Ещё вопрос как переделать скрипт лестницы под это управление?Уже неделю думаю
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using UnityEngine;
using System.Collections;
 
public class LadderScriptFotGame : MonoBehaviour
{
 
    
    private bool onLadder;
    //is this character on a ladder
    
    private bool onLadderTop;
    //is the character on the top of a ladder
    
    private bool onLadderBottom;
    //has the character hit the bottom of the ladder
    
    public bool usingRigidbodyFirstPersonControllerSetUp;
    //is the person using the RigidbodyFirstPersonController
 
    public bool usingFirstPersonControllerSetUp;
    //is the person using the RigidbodyFirstPersonController
 
    public float climbSpeed;
    //the speed the character move at on the ladder
    
    private UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController controller;
    //the RigidbodyFirstPersonController
 
 
    private UnityStandardAssets.Characters.FirstPerson.FirstPersonController controller2;
 
    private float verticalInput;
    //the vertical input
 
    private Transform topLadderPoint;
    //the top point of this ladder
 
    private bool atTargetPoint;
    //tell the script if the charcter has hit the target point when they are on the top of the ladder
 
 
 
    public void Start ()
    {
        if (transform.GetComponent<UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController> ()) {
            controller = transform.GetComponent<UnityStandardAssets.Characters.FirstPerson.RigidbodyFirstPersonController> ();
        }
        if (transform.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController> ()) {
            controller2 = transform.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController> ();
        }
    }
 
    public void Update ()
    {
        verticalInput = Input.GetAxis ("Vertical");
        if (onLadderTop) {
            if (!atTargetPoint) {
                MoveCharacterToPoint ();
                float ladderTopDistance;
                ladderTopDistance = Vector3.Distance (topLadderPoint.position, transform.position);
                if (ladderTopDistance < 0.2) {
                    StartCoroutine ("HitTopOfLadder");
                }
            }
        }
    }
    
 
    //what to do if we are in contect we a ladder object for more than a second
    void OnTriggerStay (Collider other)
    {
        if (other.GetComponent<Laddertype> ()) {
            if (verticalInput > 0.1) {
                if (other.GetComponent<Laddertype> ().isLadder) {
                    Vector3 ****CSharp;
                    //why is this named **** csharp
                    //let me tell unlike unityscript
                    //csharp doesnt let you modify a transform's x,y or z position by iself so you have to write out this long bulshit code instead 
                    ****CSharp = transform.position;
                    ****CSharp.x = other.transform.position.x;
                    ****CSharp.z = other.transform.position.z;
                    transform.position = ****CSharp;
                    transform.rotation = other.transform.rotation;
                    onLadder = true;
                }
            }  
            if (other.GetComponent<Laddertype> ().isLadderBottom) {
                if (verticalInput < -0.1f) {
                    if (onLadder) {
                        StopClimbing ();
                    }
                }
            }
            if (onLadder) {
                ClimbLadder ();
            }
        }
    }
 
 
    //what to do if we hit a ladder collider
    void OnTriggerEnter (Collider other)
    {
        if (other.GetComponent<Laddertype> ()) {
            if (other.GetComponent<Laddertype> ().isLadderTop) {
                if (usingRigidbodyFirstPersonControllerSetUp) {
                    if (controller.enabled) {
 
                    } else {
                        onLadderTop = true;
                        topLadderPoint = other.GetComponent<Laddertype> ().topLadderEndPoint;
                    }
                }
                if (usingFirstPersonControllerSetUp) {
                    if (controller2.enabled) {
 
                    } else {
                        onLadderTop = true;
                        topLadderPoint = other.GetComponent<Laddertype> ().topLadderEndPoint;
                    }
                }
            }
        }
    }
 
    //what to do the character is exiting the ladder to climb on top or something else
    void OnTriggerExit (Collider other)
    {
        if (other.GetComponent<Laddertype> ()) {
            onLadder = false;
        }
    }
 
 
    //what to do when the character hits the top of a ladder
    IEnumerator HitTopOfLadder ()
    {
        onLadderTop = false;
        atTargetPoint = true;
        StopClimbing ();
        yield return new WaitForSeconds (0.2f);
        atTargetPoint = false;
    }
 
    //moves the character from one target point to the next when on coner climbpoint//use for top of ladder
    public void MoveCharacterToPoint ()
    {
        onLadder = false;
        float speed;
        speed = climbSpeed * Time.deltaTime;
        transform.position = Vector3.MoveTowards (transform.position, topLadderPoint.position, speed);
    }
        
    
    //allows the character to climb a ladder
    public void ClimbLadder ()
    {
        if (usingRigidbodyFirstPersonControllerSetUp) {
            GetComponent<Rigidbody> ().useGravity = false;
            controller.enabled = false;
        }
        if (usingFirstPersonControllerSetUp) {
            GetComponent<Rigidbody> ().useGravity = false;
            controller2.enabled = false;
        }
        if (onLadder) {
            UseLadder ();
        }
    }
    
    
    //stops the character from climbing
    public void StopClimbing ()
    {
        if (usingRigidbodyFirstPersonControllerSetUp) {
            GetComponent<Rigidbody> ().useGravity = true;
            controller.enabled = true;
        }
        if (usingFirstPersonControllerSetUp) {
            GetComponent<Rigidbody> ().useGravity = true;
            controller2.enabled = true;
        }
        onLadder = false;
 
    }
    
    //lets the charatcer climb ladders up and down
    public void UseLadder ()
    {
        if (verticalInput > 0.1) {
            transform.Translate (Vector3.up * Time.deltaTime * climbSpeed / 7, Space.World);
        }
        if (verticalInput < -0.1f) {
            transform.Translate (Vector3.down * Time.deltaTime * climbSpeed / 7, Space.World);
        }
    }
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
24.03.2021, 17:41
Помогаю со студенческими работами здесь

Cportlib небольшая проблема
Доброго времени суток. Пытаюсь работать с компонентом, для передачи и получения байтов в порт по протоколу modbus. Тут все просто....

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

Небольшая проблема с триггером
Добрый день! Прошу сильно не ругаться, но никак не могу решить вот такой вопрос. Создаю базу (приведу для примера), в базе одна таблица -...

Небольшая проблема с wine
Как запускать программы через проводник(Nautilus) ? В данный момент запускаю программы вот так: wine путь_до_файла

Небольшая проблема с модулем
Компилятор обнаружил ошибку в конце кода (скриншот) Unit cmplx; Interface const kol1 = 9; kol2 = 14; type с =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Загрузка PNG-файла с альфа-каналом с помощью библиотеки SDL3_image на Android
8Observer8 27.01.2026
Содержание блога SDL3_image - это библиотека для загрузки и работы с изображениями. Эта пошаговая инструкция покажет, как загрузить и вывести на экран смартфона картинку с альфа-каналом, то есть с. . .
влияние грибов на сукцессию
anaschu 26.01.2026
Бифуркационные изменения массы гриба происходят тогда, когда мы уменьшаем массу компоста в 10 раз, а скорость прироста биомассы уменьшаем в три раза. Скорость прироста биомассы может уменьшаться за. . .
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru