【问题标题】:Please help me with Unity3D请帮助我使用 Unity3D
【发布时间】:2021-04-04 20:05:34
【问题描述】:

我是 Unity 新手,我希望玩家朝着摄像机的方向移动,但我找不到任何有效的答案。

我的移动代码在这里。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
    private float speed = 50000;
    

    private Rigidbody rb = null;
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
   
}


void Update()
{
    float xSpeed = Input.GetAxis("Horizontal") * speed;
    float ySpeed = Input.GetAxis("Vertical") * speed;
    Rigidbody rb = GetComponent<Rigidbody>();
    rb.AddTorque(new Vector3(xSpeed, 0, ySpeed) * speed * Time.deltaTime);

}

}

我的相机代码在这里。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cameera : MonoBehaviour
{
     public float mouseSens = 2f;
     float pitch;
     float yaw;
     public Transform target;
     public float dst = 2f;
     public Vector2 pitchMinMax = new Vector2(-80, 80);



// Update is called once per frame
void LateUpdate()
{
    yaw += Input.GetAxis("Mouse X") * mouseSens;
    pitch -= Input.GetAxis("Mouse Y") * mouseSens;
    pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);
    Vector3 targetRotation = new Vector3(pitch, yaw);
    transform.eulerAngles = targetRotation;
    transform.position = target.position - transform.forward * dst;
}

}

请帮助我,我是 Unity3D 的新手。

【问题讨论】:

  • 那么获取相机的引用并使用camera.transform.forward 向同一方向移动?
  • 你能举个例子吗?

标签: c# unity3d


【解决方案1】:

你可以做这样的事情,你可以通过 transform.forward 获得相对于空间的任何正向

//rb.AddTorque(new Vector3(xSpeed, 0, ySpeed) * speed * Time.deltaTime);
rb.AddTorque(Camera.main.transform.forward * speed * Time.deltaTime);

【讨论】:

  • 这行得通,但我想按住 W 然后朝着相机的方向前进。现在它一直都是。
  • 您需要将其与值相乘或检查是否有输入,我只是给示例给出了方向。
猜你喜欢
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2011-11-02
  • 2017-07-22
相关资源
最近更新 更多