玩家相对于相机方向的移动 C#

Posted

技术标签:

【中文标题】玩家相对于相机方向的移动 C#【英文标题】:Player Movement Relative to Camera Direction C# 【发布时间】:2021-04-18 10:57:00 【问题描述】:

我对统一制作游戏相当陌生,我正试图让我的玩家朝着相对于相机位置的方向移动。我不知道该怎么做,下面是我的代码,有人能帮我吗?

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

public class PlayerMovement : MonoBehaviour

    // Start is called before the first frame update


    public Rigidbody rb;
    public Transform cam;

    public float movementSpeed = 6.0f;      //speed the player moves at
    public float jumpHeight = 200.0f;       //height of the jump
    public float timeBetweenJumps = 1.0f;   //delay between each jump so the player can't jump again before reaching the ground
    private float timestamp;

    public Vector3 movement;
 
    void Start()
    
        rb = this.GetComponent<Rigidbody>();
    


    void Update()
    
      
        movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));     
        transform.LookAt(transform.position + new Vector3(movement.x, 0f, movement.z));         // makes the player always face in the direction of movement

        if (Time.time >= timestamp && (Input.GetKeyDown("space")))
        
            GetComponent<Rigidbody>().velocity = Vector3.up * jumpHeight;                       // multiplies the players Y position by the jumpHeight variable which causes the player to jump in-game
            timestamp = Time.time + timeBetweenJumps;

        

    
    

    void FixedUpdate()
    
        moveCharacter(movement);    

    

    void moveCharacter(Vector3 direction)
    
        rb.MovePosition(transform.position + (direction * movementSpeed * Time.deltaTime));     //moves the rigidbody (player) 
        
    


【问题讨论】:

【参考方案1】:

首先

// multiplies the players Y position by the jumpHeight variable which causes the player to jump in-game

不,它没有!您正在做的是完全替换速度,因此任何向前的速度都会被它覆盖。这是故意的吗?如果不是,它可能应该是

if (Time.time >= timestamp && (Input.GetKeyDown("space")))

    var velocity = rb.velocity;
    velocity.y = jumpHeight;
    rb.velocity = velocity;                      
    timestamp = Time.time + timeBetweenJumps;
 

那么你正在世界空间中移动。

为了考虑相机的方向,例如

[SerializeField] private Camera mainCamera;

private void Awake ()

    if(!mainCamera) mainCamera = Camera.main;   

然后

movement = mainCamera.transform.right * Input.GetAxis("Horizontal") + mainCamera.transform.forward * Input.GetAxis("Vertical"); 

所以现在输入是相对于相机的当前旋转使用的。请注意,如果相机以某种方式在其他轴上旋转,而不仅仅是 Y ...

,请注意,这可能会表现得很奇怪

【讨论】:

以上是关于玩家相对于相机方向的移动 C#的主要内容,如果未能解决你的问题,请参考以下文章

A 帧沿相机方向向前移动

移动相机以适应 3D 场景

OpenGL模拟波斯王子相机

需要一种方式让玩家朝着摄像机指向的方向移动。 (统一)

如何将“相机”移动到玩家所面对方向的左/右

带有 Unity 3D 的 C#:当用户移动鼠标时,如何使相机围绕对象移动