我正在使用Unity,并尝试将我的播放器对象移动到相对于摄像头所面对的方向。相机当前可以使用鼠标围绕播放器对象旋转/动态观察,但是,它只能相对于世界的方向移动,而不是相机。本质上,我试图复制游戏Absolver所做的事情。在4:30左右的youtube视频中有一个很好的剪辑,展示了相机/播放器的运动:https://www.youtube.com/watch?v=_lBqCTeJwYw&t=1199s。
我看过youtube视频、统一答案和涉及操纵杆、四元数和欧拉值的脚本手册,但我似乎就是找不到适合我特定问题的解决方案。任何帮助都是非常好的。提前感谢!
摄像机旋转代码:
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
private const float Y_ANGLE_MIN = 0f;
private const float Y_ANGLE_MAX = 85f;
public Transform lookAt;
public Transform camTransform;
private Camera cam;
private float distance = 10f;
private float currentX = 0f;
private float currentY = 0f;
private float sensitivityX = 5f;
private float sensitivityY = 5f;
private void Start()
{
camTransform = transform;
cam = Camera.main;
}
private void Update()
{
currentX += Input.GetAxis("Mouse X") * sensitivityX;
currentY -= Input.GetAxis("Mouse Y") * sensitivityY;
currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}
private void LateUpdate()
{
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
camTransform.position = lookAt.position + rotation * dir;
camTransform.LookAt(lookAt.position);
}
}
球员移动代码:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public Camera cam;
public float movementForce = 500f;
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey("w"))
{
rb.AddForce(0, 0, movementForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-movementForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
rb.AddForce(0, 0, -movementForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("d"))
{
rb.AddForce(movementForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
发布于 2019-03-08 13:54:23
您希望使用相机的transform.forward
属性。
如下所示:
rb.AddForce(cam.transform.forward * movementForce * Time.deltaTime, ForceMode.VelocityChange);
您还可以使用以下命令:
transform.left
transform.right
在AddForce文档中就有一个这样的例子。
https://stackoverflow.com/questions/55056306
复制相似问题