【问题标题】:Cant Change Friction of Player In Unity2DUnity2D中无法改变玩家的摩擦力
【发布时间】:2020-06-15 11:27:08
【问题描述】:

我对 Unity 和 C# 都非常陌生,并且已经研究了几天。我目前正试图阻止我的播放器滑动,为此我将播放器材料的摩擦值设置得很高,这样它就不会滑动。然而,这会产生一个问题,即我的角色移动速度过快。为了解决这个问题,我创建了一个带有 BoxCollider2D 的子对象,标记为摩擦控制器,我可以对其进行修改。我得到一个代码,当我开始移动时将物理材料的摩擦值更改为 0,当我应该停止时更改为 100。问题是虽然这会更新材质本身,但它不会影响盒子碰撞器设置。有人知道这个的解决方案吗?

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

public class Player_Movement : MonoBehaviour
{

    GameObject frictionController;
    public BoxCollider2D collider;

    public float speed = 400f;
    public float jumpForce;
    private float friction;
    private Rigidbody2D rb2d;
    private bool isMoving;
    // Start is called before the first frame update
    void Start()
    {

        rb2d = GetComponent<Rigidbody2D> ();
    }

    // Update is called once per frame

    void FixedUpdate()
    {




        float moveHorizontal = Input.GetAxis("Horizontal");


        Vector2 movement = new Vector2(moveHorizontal,0);


        rb2d.AddForce(movement * speed);


    }
    void Update()
    {
        frictionController = GameObject.FindWithTag("Friction Controller");
        collider = frictionController.GetComponent<BoxCollider2D>();



        if (Input.GetKey("a") || (Input.GetKey("d")))
        {
            { Debug.Log("Pressed Button"); }
           collider.sharedMaterial.friction = 0;

        }   else { collider.sharedMaterial.friction = 100; }
///This part isn't complete yet

        float moveVertical = Input.GetAxis("Vertical");

        Vector2 jump = new Vector2(0, moveVertical);

        if (Input.GetKeyDown("space"))
        {
            rb2d.AddForce(Vector3.up * jumpForce);
        }
    }
}

【问题讨论】:

  • 是否有可能因为Input.GetAxis 的缓动而滑动?尝试改用Input.GetAxisRaw
  • 那没用

标签: c# unity3d


【解决方案1】:

我不确定您的方法是否特别好,以后可能会给您带来问题。由于您使用的是物理系统,因此更好的方法是在刚体停止时向刚体施加一个与它的速度相反的力。

尽管如此,这里有一个解决方案,它可以使用与您正在尝试的类似方法有效地完成您想做的事情。该解决方案不是操纵物理材料属性,而是操纵刚体的阻力值。

public class Player_Movement : MonoBehaviour
{

    private Rigidbody2D rb2d;
    private float speed = 100f; 

    void Start()
    {
        rb2d = GetComponent<Rigidbody2D> ();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        Vector2 movement = new Vector2(moveHorizontal,0);
        rb2d.AddForce(movement * speed);
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.D)))
        {
           rb2d.drag = 5; // Adjust this value to modify speed
        }   
        else 
        { 
            rb2d.drag = 100; // Adjust this value to modify slippery-ness
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    相关资源
    最近更新 更多