首页 > 解决方案 > 为什么刚体播放器控制器不工作?我无法移动播放器

问题描述

该脚本附加到我的具有刚体组件的播放器上。刚体使用重力并且是运动学的被设置为ture。

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

public class RigidbodyPlayercontroller : MonoBehaviour
{
    Rigidbody rb;
    public float speed;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate()
    {
        float mH = Input.GetAxis("Horizontal");
        float mV = Input.GetAxis("Vertical");
        rb.velocity = new Vector3(mH * speed, rb.velocity.y, mV * speed);
    }
}

但是玩家没有移动它什么都不做。我尝试了速度值 1 和 100。

标签: c#unity3d

解决方案


设置velocity运动学刚体的 不会产生任何影响。如文档所述,使用MovePosition更改运动学Rigidbody的位置。

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

public class PlayerController: MonoBehaviour
{
   public float speed;

   private float vertical;
   private float horizontal;

   private Rigidbody rb;

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

   void Update()
   {
      vertical = Input.GetAxis("Vertical") * speed;
      horizontal = Input.GetAxis("Horizontal") * speed;
   }

   void FixedUpdate()
   {
      rb.MovePosition(
         transform.position +
         transform.right * horizontal * Time.fixedDeltaTime +
         transform.forward * vertical * Time.fixedDeltaTime
      );
   }
}

推荐阅读