【发布时间】:2021-06-15 00:17:44
【问题描述】:
我在 Unity 3D 中制作了一个简单的移动系统,但我不知道如何制作,以便我朝着玩家指向的方向移动。
using UnityEngine;
public class PlayerControler : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1f;
public float Gravity = 9.8f;
private float velocity = 0f;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal") * MovementSpeed;
float vertical = Input.GetAxis("Vertical") * MovementSpeed;
characterController.Move((Vector3.right * horizontal + Vector3.forward * vertical) * Time.deltaTime);
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
}
}
这是播放器控制器。
using UnityEngine;
public class MouseControl : MonoBehaviour
{
public float horizontalSpeed = 1f;
public float verticalSpeed = 1f;
private float xRotation = 0.0f;
private float yRotation = 0.0f;
private Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;
yRotation += mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
}
}
这是使我的角色面对光标所在位置的代码。
编辑:这是一款第一人称 3D 游戏。播放器上有一个 CharacterControler 组件,主摄像机是播放器的子级。第二段代码改变了光标移动时相机所面对的方向。第一个脚本是移动脚本,利用玩家的 CharacterController 组件进行移动。我想做到这一点,而不是每次按下移动键时都沿四个静态方向移动,我希望玩家与相机所面对的方向(在 X 轴上)成比例地移动。例如:如果我面向西方并按“W”前进,我希望角色向西而不是向北。
【问题讨论】:
-
This is the code that makes my character face where my cursor is.不是真的.. 它只会让你的鼠标移动以一定的灵敏度旋转播放器.. ;) -
您需要详细说明您的项目更多。根据我的理解,这是一种 第三人称 方法,带有一些等距 3D 系统(其中“前进”是有意义的)。但是,您一边旋转主摄像机一边告诉“您的角色面对光标”这一事实暗示了第一人称场景 - 在这种情况下 光标 没有什么意义。
-
@Victor-ReinstateMonica 我现在为我的问题添加了更多细节。