我创建了一个基本的第一人称 Controller ,但我的问题是当我向前和向侧面移动时我移动得更快。
我如何在 1 Vector3 中添加 moveDirectionForward
和 moveDirectionSide
以便能够使用 CharacterController.Move()
而不是 CharacterController .SimpleMove()
?
void MovePlayer() {
// Get Horizontal and Vertical Input
float horizontalInput = Input.GetAxis ("Horizontal");
float verticalInput = Input.GetAxis ("Vertical");
// Calculate the Direction to Move based on the tranform of the Player
Vector3 moveDirectionForward = transform.forward * verticalInput * walkSpeed * Time.deltaTime;
Vector3 moveDirectionSide = transform.right * horizontalInput * walkSpeed * Time.deltaTime;
// Apply Movement to Player
myCharacterController.SimpleMove (moveDirectionForward + moveDirectionSide);
最佳答案
解决方案是对运动方向使用归一化向量。
// Get Horizontal and Vertical Input
float horizontalInput = Input.GetAxis ("Horizontal");
float verticalInput = Input.GetAxis ("Vertical");
// Calculate the Direction to Move based on the tranform of the Player
Vector3 moveDirectionForward = transform.forward * verticalInput;
Vector3 moveDirectionSide = transform.right * horizontalInput;
//find the direction
Vector3 direction = (moveDirectionForward + moveDirectionSide).normalized;
//find the distance
Vector3 distance = direction * walkSpeed * Time.deltaTime;
// Apply Movement to Player
myCharacterController.Move (distance);
性能说明:
vector.normalized
is obtained fromvector/vector.magnitude
andvector.magnitude
is obtained fromsqrt(vector.sqrMagnitude)
which is heavy to process. To reduce the processing weight you can usevector/vector.sqrMagnitude
instead ofvector.normalized
but be ware the result is not exactly the same, but still is in the same direction.
now i just need to apply gravity
用重力乘以 Time.deltaTime
减去 moveDirection.y
。
您还可以使用 Vector3
和 TransformDirection
来简化和减少 MovePlayer
函数中的代码。
public float walkSpeed = 10.0f;
private Vector3 moveDirection = Vector3.zero;
public float gravity = 20.0F;
CharacterController myCharacterController = null;
void Start()
{
myCharacterController = GetComponent<CharacterController>();
}
void MovePlayer()
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= walkSpeed;
moveDirection.y -= gravity * Time.deltaTime;
myCharacterController.Move(moveDirection * Time.deltaTime);
}
关于c# - 如何正确使用 CharacterController.Move() 来移动角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50493987/