如何使播放器朝相机方向移动

问题描述

这是我的动作脚本

[Serializefield]
Vector3 movement;
[Serializefield]
KeyCode Up;
[Serializefield]
KeyCode Down;
public Rigidbody rb;

private void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    if (Input.GetKey(Up))
    {
        rb.veLocity += movement;
    }

    if (Input.GetKey(Down))
    {
        rb.veLocity -= movement;
    }
}

这是我的相机脚本

[Serializefield]
Transform transTarget;
[Serializefield]
float speed;
    
void Update()
{
    transform.position = transTarget.position;
    float h = speed * Input.GetAxis("Mouse X");
    transform.Rotate(0,h,0);  
}

基本上,如果我用相机转动180,然后按向上箭头前进,则播放机将向后退。我想解决这个问题。

解决方法

您不必创建2个单独的代码即可创建第一人称控制器,这是我认为您正在尝试的方法。您只需要执行一项交给播放器的操作即可。相机必须是播放器的子代并在其中。您必须告诉播放器,当您按向上或向下键时,它们必须朝该方向移动,首先,您必须使用函数Input.GetAxis(“ Horizo​​ntal”)来检测播放器是向上还是向下按下按下“向上”按钮时为1,按下“向下”按钮时为-1,如果按下其他任何按钮,则为0。之后,您必须告诉他巫婆ID去:在他前面的transform.formward,然后乘以您想要的速度。

[SerializeField]
Vector3 movement;
[SerializeField]
KeyCode Up;
[SerializeField]
KeyCode Down;
public Rigidbody rb;

public float Sensibility,Speed;

private void Start()
{
    rb = GetComponent<Rigidbody>();
    Cursor.lockState = CursorLockMode.Locked;
    Speed = 100;
    Sensibility = 100;

}
void FixedUpdate()
{
    float h = Sensibility * Input.GetAxis("Mouse X") * Time.deltaTime;
    transform.Rotate(Vector3.up * h);

    rb.velocity = Input.GetAxis("Vertical") * Speed * transform.forward * Time.deltaTime;
}

但这是一个非常基本的动作,我推荐此视频以了解更多信息:https://www.youtube.com/watch?v=_QajrabyTJc