我创建了一个基本的第一人称控制器但我的问题是当我向前和向侧移动时我移动得更快。
如何在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);
答案 0 :(得分:3)
解决方案是使用归一化向量作为运动方向。
// 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
来自vector/vector.magnitude
和。{vector.magnitude
是从sqrt(vector.sqrMagnitude)
获得的 处理繁重。为了减少您可以使用的加工重量vector/vector.sqrMagnitude
而不是vector.normalized
但是 洁具的结果并不完全相同,但仍然是一样的 方向。
现在我只需要应用重力
通过重力乘以moveDirection.y
减去Time.deltaTime
。
您还可以使用MovePlayer
和Vector3
来简化和缩小TransformDirection
函数中的代码。
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);
}
答案 1 :(得分:2)
当您乘以walkSpeed
时,您将需要使用两个轴的标准化向量。原因在于,无论角度如何,这都将确保您始终以相同的幅度(1)向任何方向移动。而您当前的设置具有以> 1幅度计算的非正交运动。所以这样的事情应该适合你的情况。
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 * Time.deltaTime;
Vector3 moveDirectionSide = transform.right * horizontalInput * Time.deltaTime;
// Apply Movement to Player
myCharacterController.SimpleMove((moveDirectionForward + moveDirectionSide).normalized * walkspeed);
只需将walkSpeed乘法移动到针对规范化向量的SimpleMove调用。下面的图片应该有助于可视化您遇到的问题。通过在应用步行速度之前对矢量进行归一化,无论在应用步行速度之前的哪个方向,都要确保方向矢量具有相同的幅度(在这种情况下是有效的距离)。