Unity:如何在朝向相机的方向上移动对象

时间:2019-03-08 03:29:19

标签: c# unity3d

我正在使用Unity,并尝试将播放器对象沿相对于相机所面对的方向移动。相机当前能够通过使用鼠标围绕播放器对象旋转/轨道运动,但是,它仅在相对于世界的方向上移动,而不在相机上。本质上,我正在尝试复制Absolver的功能。这段youtube视频在4:30左右有一个很好的剪辑,显示摄像机/播放器的运动: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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您要使用相机的transform.forward属性。

类似这样的东西:

rb.AddForce(cam.transform.forward * movementForce * Time.deltaTime, ForceMode.VelocityChange);

您还可以支配:

transform.left
transform.right

AddForce文档中有一个确切的例子。