我有一个跳跃脚本,但它根据JumpFactor常量的值来跳跃。我想使用JumpToPositionX(float target)方法进行跳跃。我认为我需要根据JumpToPositionX方法中目标值的大小计算JumpFactor值。我在维基百科上找到了一篇文章,但我甚至不知道从哪里开始。我没有找到关于如何在CharacterController中实现这一点的示例。
public class ExampleClass : MonoBehaviour
{
const float Speed = 6f;
const float JumpFactor = 14f;
const float Gravity = 20f;
private Vector3 moveDirection = Vector3.zero;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(1f, 0f, 0f); // Move X Direction
moveDirection *= Speed;
if (Input.GetButton("Jump"))
moveDirection.y = JumpFactor;
}
moveDirection.y -= Gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
// Method for jump, calling from other script.
void JumpToPositionX(float target)
{
}
}
Update
中获取用户输入(GetKeyDown
),因为不能保证在FixedUpdate
调用中它仍然有效 ;) 另外,我仍然会通过var xyz = GetComponent<Rigidbody>().position
获取位置,并通过GetComponent<Rigidbody>().MovePosition(xyz);
设置位置,以避免破坏物理效果 ;) 当然,你可以像往常一样缓存Rigidbody
引用。 - derHugo