簡體   English   中英

在 Unity 和 C# 中沿其面對的方向移動剛體

[英]Moving a rigid body in the direction it's facing in Unity and C#

我一直在嘗試使用我能找到的幾乎所有方法(甚至使用可怕的 transform.translate)來讓它工作,但我似乎無法讓它工作。 這只是代碼的草稿,如果還有其他方法可以解決 go 的相關問題,我將更改一些內容。

目前,他幾乎沒有移動(看起來他不知何故被卡在了地板上。)我對使用剛體移動物體還很陌生,所以我對如何解決這個問題幾乎一無所知。

這是我最新破解的腳本:

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

public class PlayerTest : MonoBehaviour
{
    public float speed = 10.0f;
    public Rigidbody rb;
    public Vector3 movement;

// Start is called before the first frame update
void Start()
{
    rb.GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown("w"))
    {
        movement = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
        }
    }
    void FixedUpdate()
    {
            moveCharacter(movement);
    }

    void moveCharacter(Vector3 direction)
    {
        rb.MovePosition(transform.position + (transform.forward * speed * Time.deltaTime));
    }
}

在您的代碼中,您的更新 function 中有您的 moveCharacter function,隨附的是固定的,現在應該可以使用。 在您的 FixedUpdate 沒有被調用之前,因此您的 moveCharacter function 效果不佳,並且您的游戲對象沒有移動。

  • 編輯1:你也應該乘以你的移動方向,更新腳本以適應它
  • 編輯2:我放錯了大括號,現在修復了
  • 編輯3:您還應該每幀更新您的移動Vector3,而不是如果按下W,則再次修復腳本。
  • 編輯 4:修復了移動錯誤(復制並粘貼整個腳本,因為我更改了更多行)

這是更新的腳本:

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

public class PlayerTest : MonoBehaviour
{
    public float speed = 10.0f;
    public Rigidbody rb;
    public Vector3 movement;

    // Start is called before the first frame update
    void Start()
    {
        rb.GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        movement = new Vector3(Input.GetAxis("Horizontal"), 1f, Input.GetAxis("Vertical"));
    
    }

    void FixedUpdate()
    {
        moveCharacter(movement);
    }

    void moveCharacter(Vector3 direction)
    {
        Vector3 offset = new Vector3(movement.x * transform.position.x, movement.y * transform.position.y, movement.z * transform.position.z);
        rb.MovePosition(transform.position + (offset * speed * Time.deltaTime));
    }
}

參考: 剛體.MovePosition

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM