【发布时间】:2018-11-28 11:56:54
【问题描述】:
我正在为我的角色创建一个移动函数(我已经做了很多次,但这次它不能正常工作),这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(Animator))]
public class Movement : MonoBehaviour {
public CharacterController controller;
public float moveSpeed;
public float jumpForce;
public float gravityScale;
public Animator animator;
private bool shiftPressed = false;
private void Update()
{
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
shiftPressed = true;
else
shiftPressed = false;
if(shiftPressed)
{
moveSpeed = 20f;
} else
{
moveSpeed = 10f;
}
Vector3 moveDirection = new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed, 0.0f, Input.GetAxis("Vertical") * moveSpeed);
if(Input.GetKey(KeyCode.Space) && controller.isGrounded)
{
moveDirection.y = jumpForce;
}
if (moveDirection != Vector3.zero)
animator.SetFloat("Speed", moveSpeed);
else if (moveDirection == Vector3.zero)
animator.SetFloat("Speed", 0f);
else if (moveDirection != Vector3.zero)
animator.SetFloat("Speed", moveSpeed);
if(moveDirection != Vector3.zero)
transform.rotation = Quaternion.LookRotation(moveDirection);
moveDirection = Camera.main.transform.TransformDirection(moveDirection);
moveDirection.y = moveDirection.y + (Physics.gravity.y * Time.deltaTime * gravityScale);
controller.Move(moveDirection * Time.deltaTime);
}
}
正如你所见,除了跳转函数之外,在 y 轴上没有任何函数可以向上移动。神秘的是,当我按下“S”键或“向下箭头”时,玩家会按照他应该的方式移动 -z,但具有讽刺意味的是,他也会在 +y 轴上移动。为确保没有 y 轴功能,我尝试将跳转功能设为注释,但仍然采用相同的方式。我认为这可能是一些特定于角色的问题,所以我尝试将代码添加到立方体(认为这是我的动画错误),但它在任何时候都没有帮助。我确保角色控制器设置得很好(对撞机和其他东西);我附上了截图。 请帮忙! 提前致谢。
【问题讨论】:
-
最后一个
moveDirection.y分配可能应该在您调用TransformDirection之前? -
或者应该是
-而不是+? (Physics.gravity.y和gravityScale的值是多少?) -
这使玩家在 x 上旋转 -90 度。由于真正翻转的力量黛西
-
+10 重力比例和physics.gravity的默认9.8
-
那么你在这里不断增加
moveDirection.y...你为什么不指望这会提升你的角色呢?
标签: c# animation unity3d scripting