施加力后Unity Rigidbody2d.addforce不会改变方向

时间:2019-10-17 21:50:08

标签: unity3d physics multiplayer

存在一个问题,即2D游戏(空间)在尝试使用带有addforce的RB2D来移动玩家。似乎我可以一次选择两个方向。如果我按下,播放器会下降,但按下时不会上升,但会停止。与左/右相同。重力设置为0。两个对象都具有刚体2d,因此我需要动态以允许游戏中“弹跳”和其他物理作用。

  • 始终显示对象(运动脚本)
    • 玩家Sprite(精灵)

我希望玩家能够向上,向下,向左,向右移动。我真的同意它具有减慢效果,但不是必需的。 (如果您放开按键,它会因摩擦而减慢速度) enter image description here

我的播放器设置为分层格式,因为它是多人游戏,并且父对象始终在游戏中。

我尝试了以下方法 -在两个或每个上互换动态+运动。 -添加力,变换,速度等 -调整后的摩擦力,阻力等 -已检查的调试x / y力正在游戏中施加,但玩家在第一次移动后不会朝相反方向移动。

我已将文件上传到github here.

玩家运动

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

public class PlayerUnit : NetworkBehaviour {
    //float speed = .5F;
    float rotationSpeed = 50.0F;

    float xMin;
    float xMax;
    float yMin;
    float yMax;
    // configuration parameters
    [Header("Player")]
    [SerializeField] float moveSpeed = .5f;
    [SerializeField] float padding = 1f;
    [SerializeField] int health = 200;
    [SerializeField] AudioClip deathSound;
    [SerializeField] [Range(0, 1)] float deathSoundVolume = 0.75f;
    [SerializeField] AudioClip shootSound;
    [SerializeField] [Range(0, 1)] float shootSoundVolume = 0.25f;

    Rigidbody2D rb;

    void Start () {
       rb = this.GetComponent<Rigidbody2D>();
    }


    void Update () {

        if( hasAuthority == false )
        {
            return;
        }
        if ( Input.GetKeyDown(KeyCode.Space) )
        {
            this.transform.Translate( 0, 1, 0 );
        }     
    }

    private void FixedUpdate()
    {
        if (true)
        {
            float leftright = Input.GetAxis("Horizontal");
            float updown = Input.GetAxis("Vertical");
            float xForce = leftright * moveSpeed * Time.deltaTime;
            float yForce = updown * moveSpeed * Time.deltaTime;
            Vector2 force = new Vector2(xForce, yForce);

            rb.AddForce(force);
            Debug.Log("xForce : " + xForce + "      yForce : " + yForce);

            //float leftright = Input.GetAxis("Horizontal") * moveSpeed;
            //float updown = Input.GetAxis("Vertical") * moveSpeed;
            ////rb.MovePosition(rb.position + new Vector2(1, 0) * leftright);
            //rb.MovePosition(transform.position + (transform.right * leftright + transform.up * updown) * moveSpeed);

            //rb.MovePosition(rb.position + new Vector2(0, 1) * updown);
        }
    }
}

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码很好,您只需删除Rigidbody2D的子代上的PlayerParentObject。玩家上唯一的Rigidbody2D应该和Player Unit脚本位于同一游戏对象上。