【发布时间】:2020-09-26 21:05:10
【问题描述】:
我对 unity 很陌生,我有两个脚本,顾名思义,一个用于重力,一个用于玩家运动。我使用重力脚本的原因是第三人称运动不支持使用启用了位置和旋转的刚体,所以我冻结了刚体内的位置和旋转(这会关闭刚体中的重力)。我自己制作了 Gravity 脚本,但我遵循了关于玩家移动脚本的教程,因为我不知道如何制作第三人称移动,所以我真的不知道移动脚本中发生了什么。
运动脚本:
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
UnityEngine.Vector3 direction = new UnityEngine.Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = UnityEngine.Quaternion.Euler(0f, angle, 0f);
UnityEngine.Vector3 moveDir = UnityEngine.Quaternion.Euler(0f, targetAngle, 0f) * UnityEngine.Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
重力脚本:
public class gravityScript : MonoBehaviour
{
public float GravitySpeed = -0.03f;
public bool GravityCheck = false;
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Terrain0_0")
{
GravityCheck = true;
}
}
void OnCollisionExit(Collision col)
{
GravityCheck = false;
}
void Update()
{
if (GravityCheck == false)
{
transform.Translate(0, GravitySpeed, 0);
}
}
}
提前谢谢你:)
【问题讨论】:
-
在 OnCollisionEnter 和 OnCollisionExit 中添加一个 Debug.Log 并尝试查看这些事件何时被触发以及它们是否被触发。我还建议将 GravityCheck 重命名为 applyGravity 并使用 if 语句
if (applyGravity == true)。 GravityCheck 这个词和它的含义让我有好几次失望。
标签: c# unity3d game-physics game-development