質問するログイン新規登録

質問編集履歴

4

質問内容を変更

2019/08/26 01:56

投稿

yoshiteru21
yoshiteru21

スコア44

title CHANGED
File without changes
body CHANGED
@@ -3,140 +3,249 @@
3
3
  原因をご教授ください。
4
4
  タグはしっかり設定しています。
5
5
  デバッグログで接触していることも検知してあります。
6
- プレイヤーを動かしているスクリプト、
7
- を動かしているスクリプトを貼っています。
6
+ プレイヤーを動かしているスクリプトを貼っています。
7
+ もう一つスクリプトがありますが、関係ないとみて貼っていません。
8
+ ```namespace UnityStandardAssets.Characters.ThirdPerson
9
+ {
10
+ [RequireComponent(typeof(Rigidbody))]
11
+ [RequireComponent(typeof(CapsuleCollider))]
12
+ [RequireComponent(typeof(Animator))]
13
+ public class ThirdPersonCharacter : MonoBehaviour
14
+ {
15
+ [SerializeField] float m_MovingTurnSpeed = 360;
16
+ [SerializeField] float m_StationaryTurnSpeed = 180;
17
+ [SerializeField] float m_JumpPower = 12f;
18
+ [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
19
+ [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
20
+ [SerializeField] float m_MoveSpeedMultiplier = 1f;
21
+ [SerializeField] float m_AnimSpeedMultiplier = 1f;
22
+ [SerializeField] float m_GroundCheckDistance = 0.1f;
8
23
 
24
+ Rigidbody m_Rigidbody;
25
+ Animator m_Animator;
9
- ``` using System;
26
+ bool m_IsGrounded;
27
+ float m_OrigGroundCheckDistance;
28
+ const float k_Half = 0.5f;
29
+ float m_TurnAmount;
30
+ float m_ForwardAmount;
31
+ Vector3 m_GroundNormal;
32
+ float m_CapsuleHeight;
33
+ Vector3 m_CapsuleCenter;
34
+ CapsuleCollider m_Capsule;
10
- using UnityEngine;
35
+ bool m_Crouching;
11
- using UnityStandardAssets.CrossPlatformInput;
12
- using System.Collections;
13
- using System.Collections.Generic;
14
36
 
15
- namespace UnityStandardAssets.Characters.ThirdPerson
16
- {
17
- [RequireComponent(typeof (ThirdPersonCharacter))]
18
- public class ThirdPersonUserControl : MonoBehaviour
19
- {
20
- private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
21
- private Transform m_Cam; // A reference to the main camera in the scenes transform
22
- private Vector3 m_CamForward; // The current forward direction of the camera
23
- private Vector3 m_Move;
24
- private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
25
37
 
26
-
27
- private void Start()
38
+ void Start()
28
- {
39
+ {
29
- // get the transform of the main camera
40
+ m_Animator = GetComponent<Animator>();
41
+ m_Rigidbody = GetComponent<Rigidbody>();
42
+ m_Capsule = GetComponent<CapsuleCollider>();
30
- if (Camera.main != null)
43
+ m_CapsuleHeight = m_Capsule.height;
31
- {
32
- m_Cam = Camera.main.transform;
44
+ m_CapsuleCenter = m_Capsule.center;
33
- }
34
- else
35
- {
36
- Debug.LogWarning(
37
- "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
38
- // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
39
- }
40
45
 
41
- // get the third person character ( this should never be null due to require component )
46
+ m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
42
- m_Character = GetComponent<ThirdPersonCharacter>();
47
+ m_OrigGroundCheckDistance = m_GroundCheckDistance;
43
- }
48
+ }
44
49
 
45
50
 
46
- private void Update()
51
+ public void Move(Vector3 move, bool crouch, bool jump)
47
- {
52
+ {
48
- if (!m_Jump)
49
- {
50
- m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
51
- }
52
- }
53
53
 
54
+ // convert the world relative moveInput vector into a local-relative
55
+ // turn amount and forward amount required to head in the desired
56
+ // direction.
57
+ if (move.magnitude > 1f) move.Normalize();
58
+ move = transform.InverseTransformDirection(move);
59
+ CheckGroundStatus();
60
+ move = Vector3.ProjectOnPlane(move, m_GroundNormal);
61
+ m_TurnAmount = Mathf.Atan2(move.x, move.z);
62
+ m_ForwardAmount = move.z;
54
63
 
55
- // Fixed update is called in sync with physics
56
- private void FixedUpdate()
57
- {
58
- // read inputs
64
+ ApplyExtraTurnRotation();
59
- float h = CrossPlatformInputManager.GetAxis("Horizontal");
60
- float v = CrossPlatformInputManager.GetAxis("Vertical");
61
- bool crouch = Input.GetKey(KeyCode.C);
62
65
 
63
- // calculate move direction to pass to character
66
+ // control and velocity handling is different when grounded and airborne:
64
- if (m_Cam != null)
67
+ if (m_IsGrounded)
65
- {
68
+ {
66
- // calculate camera relative direction to move:
67
- m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
68
- m_Move = v*m_CamForward + h*m_Cam.right;
69
+ HandleGroundedMovement(crouch, jump);
69
- }
70
+ }
70
- else
71
+ else
71
- {
72
+ {
72
- // we use world-relative directions in the case of no main camera
73
- m_Move = v*Vector3.forward + h*Vector3.right;
73
+ HandleAirborneMovement();
74
- }
74
+ }
75
+
76
+ ScaleCapsuleForCrouching(crouch);
77
+ PreventStandingInLowHeadroom();
78
+
79
+ // send input and other state parameters to the animator
80
+ UpdateAnimator(move);
81
+ }
82
+
83
+
84
+ void ScaleCapsuleForCrouching(bool crouch)
85
+ {
86
+ if (m_IsGrounded && crouch)
87
+ {
88
+ if (m_Crouching) return;
89
+ m_Capsule.height = m_Capsule.height / 2f;
90
+ m_Capsule.center = m_Capsule.center / 2f;
91
+ m_Crouching = true;
92
+ }
93
+ else
94
+ {
95
+ Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
96
+ float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
97
+ if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
98
+ {
99
+ m_Crouching = true;
100
+ return;
101
+ }
102
+ m_Capsule.height = m_CapsuleHeight;
103
+ m_Capsule.center = m_CapsuleCenter;
104
+ m_Crouching = false;
105
+ }
106
+ }
107
+
108
+ void PreventStandingInLowHeadroom()
109
+ {
110
+ // prevent standing up in crouch-only zones
75
- #if !MOBILE_INPUT
111
+ if (!m_Crouching)
112
+ {
113
+ Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
114
+ float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
115
+ if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
116
+ {
117
+ m_Crouching = true;
118
+ }
119
+ }
120
+ }
121
+
122
+
123
+ void UpdateAnimator(Vector3 move)
124
+ {
125
+ // update the animator parameters
126
+ m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
127
+ m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
128
+ m_Animator.SetBool("Crouch", m_Crouching);
129
+ m_Animator.SetBool("OnGround", m_IsGrounded);
130
+ if (!m_IsGrounded)
131
+ {
132
+ m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
133
+ }
134
+
135
+ // calculate which leg is behind, so as to leave that leg trailing in the jump animation
136
+ // (This code is reliant on the specific run cycle offset in our animations,
137
+ // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
138
+ float runCycle =
139
+ Mathf.Repeat(
140
+ m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
141
+ float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
142
+ if (m_IsGrounded)
143
+ {
144
+ m_Animator.SetFloat("JumpLeg", jumpLeg);
145
+ }
146
+
147
+ // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
148
+ // which affects the movement speed because of the root motion.
149
+ if (m_IsGrounded && move.magnitude > 0)
150
+ {
151
+ m_Animator.speed = m_AnimSpeedMultiplier;
152
+ }
153
+ else
154
+ {
155
+ // don't use that while airborne
156
+ m_Animator.speed = 1;
157
+ }
158
+ }
159
+
160
+
161
+ void HandleAirborneMovement()
162
+ {
76
- // walk speed multiplier
163
+ // apply extra gravity from multiplier:
164
+ Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
165
+ m_Rigidbody.AddForce(extraGravityForce);
166
+
167
+ m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
168
+ }
169
+
170
+
77
- if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
171
+ void HandleGroundedMovement(bool crouch, bool jump)
172
+ {
173
+ // check whether conditions are right to allow a jump:
174
+ if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
175
+ {
176
+ // jump!
177
+ m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
178
+ m_IsGrounded = false;
179
+ m_Animator.applyRootMotion = false;
180
+ m_GroundCheckDistance = 0.1f;
181
+ }
182
+ }
183
+
184
+ void ApplyExtraTurnRotation()
185
+ {
186
+ // help the character turn faster (this is in addition to root rotation in the animation)
187
+ float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
188
+ transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
189
+ }
190
+
191
+
192
+ public void OnAnimatorMove()
193
+ {
194
+ // we implement this function to override the default root motion.
195
+ // this allows us to modify the positional speed before it's applied.
196
+ if (m_IsGrounded && Time.deltaTime > 0)
197
+ {
198
+ Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
199
+
200
+ // we preserve the existing y part of the current velocity.
201
+ v.y = m_Rigidbody.velocity.y;
202
+ m_Rigidbody.velocity = v;
203
+ }
204
+ }
205
+
206
+
207
+ void CheckGroundStatus()
208
+ {
209
+ RaycastHit hitInfo;
210
+ #if UNITY_EDITOR
211
+ // helper to visualise the ground check ray in the scene view
212
+ Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
78
213
  #endif
214
+ // 0.1f is a small offset to start the ray from inside the character
215
+ // it is also good to note that the transform position in the sample assets is at the base of the character
216
+ if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
217
+ {
218
+ m_GroundNormal = hitInfo.normal;
219
+ m_IsGrounded = true;
220
+ m_Animator.applyRootMotion = true;
221
+ }
222
+ else
223
+ {
224
+ m_IsGrounded = false;
225
+ m_GroundNormal = Vector3.up;
226
+ m_Animator.applyRootMotion = false;
227
+ }
79
228
 
80
- // pass all parameters to the character control script
81
- m_Character.Move(m_Move, crouch, m_Jump);
82
- m_Jump = false;
83
- }
229
+ }
84
230
 
231
+
85
- void OnCollisionStay(Collision col)
232
+ void OnCollisionEnter(Collision col)
86
233
  {
87
234
  if (col.gameObject.tag == "MoveStage")
88
235
  {
89
- transform.parent = col.gameObject.transform;
236
+ transform.SetParent(col.transform);
90
- Debug.Log("parenting");
91
237
  }
92
238
  }
239
+
93
- void OnCollisionExit()
240
+ void OnCollisionExit(Collision col)
94
241
  {
242
+ if (col.gameObject.tag == "MoveStage")
243
+ {
95
- transform.parent = null;
244
+ transform.SetParent(null);
96
- Debug.Log("exit");
245
+ }
97
246
  }
98
247
 
99
248
  }
100
249
  }
101
-
102
250
  コード
103
- ```
104
-
105
- ``` Vector3 initPosition;
106
- Vector3 newPosition;
107
-
108
- public float distance = 1f;
109
- private List<Rigidbody> _rigidbodies = new List<Rigidbody>();
110
-
111
- // Use this for initialization
112
- void Start()
113
- {
114
- /*
115
- このスクリプトを付けたゲームオブジェクト(this)の
116
- トランスフォームコンポーネント(transform)の
117
- 位置(position)をinitPositionに格納している。
118
- */
119
- initPosition = this.transform.position;
120
- }
121
-
122
- // Update is called once per frame
123
- void Update()
124
- {
125
- /*
126
- プッシャーが反復運動するよう、フレーム毎に位置を更新している。
127
- ここでは、z軸方向に反復運動するようにしている。
128
- 反復運動の移動モデルはsin関数である。
129
- */
130
- newPosition = new Vector3(initPosition.x + distance * Mathf.Sin(Time.time),
131
- initPosition.y,
132
- initPosition.z);
133
- /*
134
- Start関数内ではthis.transform.positionにてゲームオブジェクトの
135
- トランスフォームコンポーネントの情報を取得していた。
136
- トランスフォームコンポーネント以外のコンポーネントは
137
- GetComponent()の様に取得する必要がある(Unity5から)。
138
- */
139
- this.GetComponent<Rigidbody>().MovePosition(newPosition);
140
- }
141
- コード
142
251
  ```

3

質問内容の修正

2019/08/26 01:56

投稿

yoshiteru21
yoshiteru21

スコア44

title CHANGED
File without changes
body CHANGED
@@ -3,6 +3,8 @@
3
3
  原因をご教授ください。
4
4
  タグはしっかり設定しています。
5
5
  デバッグログで接触していることも検知してあります。
6
+ プレイヤーを動かしているスクリプト、
7
+ 床を動かしているスクリプトを貼っています。
6
8
 
7
9
  ``` using System;
8
10
  using UnityEngine;
@@ -98,4 +100,43 @@
98
100
  }
99
101
 
100
102
  コード
103
+ ```
104
+
105
+ ``` Vector3 initPosition;
106
+ Vector3 newPosition;
107
+
108
+ public float distance = 1f;
109
+ private List<Rigidbody> _rigidbodies = new List<Rigidbody>();
110
+
111
+ // Use this for initialization
112
+ void Start()
113
+ {
114
+ /*
115
+ このスクリプトを付けたゲームオブジェクト(this)の
116
+ トランスフォームコンポーネント(transform)の
117
+ 位置(position)をinitPositionに格納している。
118
+ */
119
+ initPosition = this.transform.position;
120
+ }
121
+
122
+ // Update is called once per frame
123
+ void Update()
124
+ {
125
+ /*
126
+ プッシャーが反復運動するよう、フレーム毎に位置を更新している。
127
+ ここでは、z軸方向に反復運動するようにしている。
128
+ 反復運動の移動モデルはsin関数である。
129
+ */
130
+ newPosition = new Vector3(initPosition.x + distance * Mathf.Sin(Time.time),
131
+ initPosition.y,
132
+ initPosition.z);
133
+ /*
134
+ Start関数内ではthis.transform.positionにてゲームオブジェクトの
135
+ トランスフォームコンポーネントの情報を取得していた。
136
+ トランスフォームコンポーネント以外のコンポーネントは
137
+ GetComponent()の様に取得する必要がある(Unity5から)。
138
+ */
139
+ this.GetComponent<Rigidbody>().MovePosition(newPosition);
140
+ }
141
+ コード
101
142
  ```

2

質問内容の修正

2019/08/23 05:49

投稿

yoshiteru21
yoshiteru21

スコア44

title CHANGED
File without changes
body CHANGED
File without changes

1

質問内容の修正

2019/08/23 05:47

投稿

yoshiteru21
yoshiteru21

スコア44

title CHANGED
File without changes
body CHANGED
@@ -2,38 +2,100 @@
2
2
  しかし、プレイヤーだけ動かず着地地点に固定されたままです。
3
3
  原因をご教授ください。
4
4
  タグはしっかり設定しています。
5
+ デバッグログで接触していることも検知してあります。
5
6
 
7
+ ``` using System;
8
+ using UnityEngine;
9
+ using UnityStandardAssets.CrossPlatformInput;
10
+ using System.Collections;
11
+ using System.Collections.Generic;
12
+
13
+ namespace UnityStandardAssets.Characters.ThirdPerson
14
+ {
15
+ [RequireComponent(typeof (ThirdPersonCharacter))]
6
- ``` public Vector3 defaultScale = Vector3.zero;
16
+ public class ThirdPersonUserControl : MonoBehaviour
7
- void Start ()
8
17
  {
18
+ private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
19
+ private Transform m_Cam; // A reference to the main camera in the scenes transform
20
+ private Vector3 m_CamForward; // The current forward direction of the camera
9
- defaultScale = transform.lossyScale;
21
+ private Vector3 m_Move;
10
- }
11
-
12
- void Update ()
13
- {
14
- Vector3 lossScale = transform.lossyScale;
15
- Vector3 localScale = transform.localScale;
16
- transform.localScale = new Vector3(
17
- localScale.x / lossScale.x * defaultScale.x,
22
+ private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
18
- localScale.y / lossScale.y * defaultScale.y,
19
- localScale.z / lossScale.z * defaultScale.z
20
- );
21
- }
22
23
 
23
- void OnCollisionEnter(Collision collision) {
24
+
24
- if (transform.parent == null && collision.gameObject.tag == "MoveFloor") {
25
- var emptyObject = new GameObject();
25
+ private void Start()
26
+ {
26
- emptyObject.transform.parent = collision.gameObject.transform;
27
+ // get the transform of the main camera
28
+ if (Camera.main != null)
29
+ {
27
- transform.parent = emptyObject.transform;
30
+ m_Cam = Camera.main.transform;
28
- }
31
+ }
32
+ else
33
+ {
34
+ Debug.LogWarning(
35
+ "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
36
+ // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
37
+ }
29
38
 
39
+ // get the third person character ( this should never be null due to require component )
40
+ m_Character = GetComponent<ThirdPersonCharacter>();
30
- }
41
+ }
31
42
 
43
+
32
- void OnCollisionExit(Collision collision){
44
+ private void Update()
33
- if (transform.parent != null && collision.gameObject.tag == "MoveFloor")
34
- {
45
+ {
46
+ if (!m_Jump)
47
+ {
48
+ m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
49
+ }
50
+ }
51
+
52
+
53
+ // Fixed update is called in sync with physics
54
+ private void FixedUpdate()
55
+ {
56
+ // read inputs
57
+ float h = CrossPlatformInputManager.GetAxis("Horizontal");
58
+ float v = CrossPlatformInputManager.GetAxis("Vertical");
59
+ bool crouch = Input.GetKey(KeyCode.C);
60
+
61
+ // calculate move direction to pass to character
62
+ if (m_Cam != null)
63
+ {
64
+ // calculate camera relative direction to move:
65
+ m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
66
+ m_Move = v*m_CamForward + h*m_Cam.right;
67
+ }
68
+ else
69
+ {
70
+ // we use world-relative directions in the case of no main camera
71
+ m_Move = v*Vector3.forward + h*Vector3.right;
72
+ }
73
+ #if !MOBILE_INPUT
74
+ // walk speed multiplier
75
+ if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
76
+ #endif
77
+
78
+ // pass all parameters to the character control script
79
+ m_Character.Move(m_Move, crouch, m_Jump);
80
+ m_Jump = false;
81
+ }
82
+
83
+ void OnCollisionStay(Collision col)
84
+ {
85
+ if (col.gameObject.tag == "MoveStage")
86
+ {
87
+ transform.parent = col.gameObject.transform;
88
+ Debug.Log("parenting");
89
+ }
90
+ }
91
+ void OnCollisionExit()
92
+ {
35
- transform.parent = null;
93
+ transform.parent = null;
94
+ Debug.Log("exit");
36
- }
95
+ }
96
+
37
- }
97
+ }
98
+ }
99
+
38
100
  コード
39
101
  ```