【问题标题】:The player will not move where the camera is facing玩家不会移动到相机面对的地方
【发布时间】:2017-02-21 20:15:23
【问题描述】:

当我按住“w”键并移动相机时,玩家不会向相机方向移动,例如,如果我向前移动相机向左移动,它不会向左移动而是继续向前,什么是一些可能的方法来解决这个问题。玩家移动脚本

    public float movementspeed = 5.0F;

// Use this for initialization
void Start () {
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update () {

    float translation = Input.GetAxis("Vertical") * movementspeed;
    float straffe = Input.GetAxis("Horizontal") * movementspeed;
    translation *= Time.deltaTime;
    straffe *= Time.deltaTime;

    transform.Translate(straffe, 0, translation);
}

}

和相机视图脚本

    public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;

public float yMaxLimit = 50.0f;
public float yMinLimit = -50.0f;


float yRotCounter = 0.0f;
float xRotCounter = 0.0f;

Transform player;

void Start()
{
    player = Camera.main.transform;
}

// Update is called once per frame
void Update()
{
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
    yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
    //xRotCounter = xRotCounter % 360;//Optional
    player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}

}

【问题讨论】:

  • 我将第一个脚本附加到相机上,第二个脚本为空游戏对象。我能够移动和旋转相机。搬家没问题。它总是移动到相机所面对的方向。你遇到了什么问题?
  • 假设我向左看,然后按'w'它不会向左。移动方向不会随着相机而改变,无论我面对什么方向它都会以特定的方式移动,比如如果我向前看并按下'w'并且不触摸相机,它就会去直线,但如果我转动相机回头看并按“w”,它会倒退
  • 使用您在问题中更新的图像,不要在游戏对象下方放置一个摄像头。反过来做。使该 Player 成为 Camera 的子对象,然后将两个脚本附加到 Camera,该 Camera 现在是 Player 的父对象。
  • 我将玩家作为相机的子节点,两个脚本都附加到相机上,现在它主要移动相机
  • 我刚刚注意到它有刚体。禁用 Use Gravity 选项。

标签: c# unity3d unity5


【解决方案1】:

您需要使用 de camera transform 才能做到这一点。比如:

public float movementspeed = 5.0F;
public Transform cameraTransform;

// Use this for initialization
void Start () {
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update () {

    float translation = Input.GetAxis("Vertical") * movementspeed;
    float straffe = Input.GetAxis("Horizontal") * movementspeed;
    translation *= Time.deltaTime;
    straffe *= Time.deltaTime;

    Vector3 movement = cameraTransform.Forward * translation + cameraTransform.Right * straffe;
    transform.position = transform.position+ movement;
}

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多