Unity3D Player 运动脚本
Unity3D Player movement script
我有一个脚本可以让你控制一个玩家,然后跳跃。
但是,我正在努力让玩家不断移动,而不是通过键盘上的 WASD 键进行控制。
每当我尝试只使用 controller.Move()
时,我的重力功能就会消失。
现在,使用此代码 Gravity 可以工作,但 WASD 也已启用。
我的问题是:如何让这段代码让我的玩家不断移动,并且仍然使用重力?
using UnityEngine;
using System.Collections;
public class PlayerMotor : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.back;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
controller.Move (Vector3.back * Time.deltaTime);
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Whenever I try to only use controller.Move() my Gravity function goes away
这是文档中所述的预期行为:https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
不是从玩家那里获取输入,而是指定您自己的 moveDirection
。例如:moveDirection = new Vector3(1, 0, 1);
查看文档以了解可能的值:https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
旁注:CharacterController controller = GetComponent<CharacterController>();
我知道您是从文档中复制的,但是 GetComponent
每次更新都不是性能明智的。缓存它!
我有一个脚本可以让你控制一个玩家,然后跳跃。
但是,我正在努力让玩家不断移动,而不是通过键盘上的 WASD 键进行控制。
每当我尝试只使用 controller.Move()
时,我的重力功能就会消失。
现在,使用此代码 Gravity 可以工作,但 WASD 也已启用。
我的问题是:如何让这段代码让我的玩家不断移动,并且仍然使用重力?
using UnityEngine;
using System.Collections;
public class PlayerMotor : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.back;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
controller.Move (Vector3.back * Time.deltaTime);
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Whenever I try to only use controller.Move() my Gravity function goes away
这是文档中所述的预期行为:https://docs.unity3d.com/ScriptReference/CharacterController.Move.html
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
不是从玩家那里获取输入,而是指定您自己的 moveDirection
。例如:moveDirection = new Vector3(1, 0, 1);
查看文档以了解可能的值:https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
旁注:CharacterController controller = GetComponent<CharacterController>();
我知道您是从文档中复制的,但是 GetComponent
每次更新都不是性能明智的。缓存它!