如何在 Unity 中的第一人称射击游戏中进行刚体运动?

问题描述 投票:0回答:2

所以我正在Unity中制作FPS游戏,我曾经使用transform.translate进行移动,但这允许玩家在移动足够快的情况下穿过墙壁(对角线移动),甚至无论墙壁有多大命中框是。

这是我的播放器控制器代码:

https://pastebin.com/6g7j8G6v

这是运动代码:

void FixedUpdate()
{
    myBody.MovePosition(transform.position + (transform.forward * 
    Time.deltaTime * speed));
}

void Update()
{

float axisX = Input.GetAxis ("Horizontal");
float axisY = Input.GetAxis ("Vertical");

更多信息:使用此代码,玩家现在可以朝非常特定的方向移动,无论旋转如何。另外,W 和 S 是上下移动,而不是前后移动。

c# unity-game-engine 3d game-physics rigid-bodies
2个回答
2
投票

我建议你查看https://learn.unity.com/tutorial/environment-and-player?projectId=5c51479fedbc2a001fd5bb9f#5c7f8529edbc2a002053b786 unity官方文档

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

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

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

        rb.AddForce (movement * speed);
    }
}

他们有一个非常简单的示例代码来说明如何做到这一点,请记住,该解决方案仍然需要标准化矢量运动,为此,请执行以下操作:

rb.AddForce (movement.normalized  * speed);

0
投票
public float speed;
public float rotationspeed;
 
void Update()
{
    transform.Translate(Vector3.up * speed * Time.deltaTime);
    if (Input.GetKey(KeyCode.RightArrow))
    {

        transform.Rotate(new Vector3(0, 0, -1) * rotationspeed * Time.deltaTime);

    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {

        transform.Rotate(new Vector3(0, 0, 1) * rotationspeed * Time.deltaTime);

    }
}
public void restar()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
© www.soinside.com 2019 - 2024. All rights reserved.