如何在Unity3D中为一个财富之轮添加摩擦力

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

首先,我和C#一样对团结不熟悉。我想用C#为我的游戏创建一个财富之轮,你可以用鼠标旋转它。我在C#中编写了这段代码 - 它运行良好,唯一的问题是我不知道如何为它添加摩擦力,这样如果我释放鼠标按钮它仍然继续旋转并减速直到它完全停止(就像一个现实的财富轮)。

using UnityEngine;
using System.Collections;

public class RotateCSharp : MonoBehaviour
{
    public int speed;
    public float lerpSpeed;
    float xDeg;
    float yDeg;
    Quaternion fromRotation;
    Quaternion toRotation;


    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            xDeg -= Input.GetAxis("Mouse X") * speed;
            fromRotation = transform.rotation;
            toRotation = Quaternion.Euler (yDeg,xDeg,0);
            transform.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);
        }
    }
}

我怎么能做到这一点?

unity3d
2个回答
1
投票

完全披露 - 我不做Unity,也不做C#,但这主要是数学。

滑动或滚动的摩擦几乎是恒定的减速度。减速度为负加速度,加速度为(速度变化)/(经过时间)。

计算您希望车轮以您允许的最大初始角速度旋转多长时间,并且速度/时间比率是您的减速率。这是车轮的常数。

现在,在调整角度位置之前或之后的代码中,通过减速率*时间间隔降低速度,注意不要超过0:

if (speed > 0)
    speed = Math.max(0, speed - decelRate*Time.deltaTime);
else 
    speed = Math.min(0, speed + decelRate*Time.deltaTime);

这假设decelRate是一个正值,并将处理任一方向的旋转。

您可能需要稍微调整一下语法,但这是基本的想法。


0
投票

我把一种在铰链接头上施加摩擦的行为放在一起。这里是:

using UnityEngine;

public class JointFriction : MonoBehaviour {

  [Tooltip("mulitiplier for the angular velocity for the torque to apply.")]
  public float Friction = 0.4f;

  private HingeJoint _hinge;
  private Rigidbody _thisBody;
  private Rigidbody _connectedBody;
  private Vector3 _axis;  //local space

  // Use this for initialization
  void Start () {
    _hinge = GetComponent<HingeJoint>();
    _connectedBody = _hinge.connectedBody;
    _axis = _hinge.axis;

    _thisBody = GetComponent<Rigidbody>();
  }

  // Update is called once per frame
  void FixedUpdate () {
    var angularV = _hinge.velocity;
    //Debug.Log("angularV " + angularV);
    var worldAxis = transform.TransformVector(_axis);
    var worldTorque = Friction * angularV * worldAxis;

    _thisBody.AddTorque(-worldTorque);
    _connectedBody.AddTorque(worldTorque);
  }
}

您可以将此作为单独的行为应用于具有铰链接头的对象,或者您可以将其取出并将其合并到您的行为中。

此代码假定铰链接头具有连接的刚体,如果不是这样,则只需移除引用_connectedRigidbody的线。

© www.soinside.com 2019 - 2024. All rights reserved.