【问题标题】:Player Movement Relative to Camera Direction C#玩家相对于相机方向的移动 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) 
        
    }
}

【问题讨论】:

    标签: c# unity3d camera


    【解决方案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 ...

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

    【讨论】:

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