How to simulate car moving 2D via WheelJoint2D.motorSpeed?

Viewed 91

Please, help me. The farther from the center of the screen the higher / lower the car speed. Car's RigidBody2D.mass = 1000, wheels's mass = 50. The car object has 2 'WheelJoint2D' components (connected RigidBody = frontwheel and backwheel) and useMotor = true, maximumMotorForce = 10000 (by default).

Here is part of my code (C#):

[RequireComponent(typeof(Rigidbody2D), typeof(WheelJoint2D))]
public class CarBaseMovement : MonoBehaviour, IVehicleMovable
{
    public const float GRAVITY = 9.81f;

    [Header("Wheels Joint")]
[SerializeField] protected WheelJoint2D _frontWheelJoint;
[SerializeField] protected WheelJoint2D _backWheelJoint;

private int _centerScreenX;

protected Rigidbody2D _rigidBody2D;

private float _movementInput;
private float _deltaMovement;

private float _physicValue;

private JointMotor2D _wheelMotor;

private void Start()
{
    // set center screen width
    _centerScreenX = Screen.width / 2;

    _rigidBody2D = GetComponent<Rigidbody2D>();

    if (_rigidBody2D == null || _frontWheelJoint == null || _backWheelJoint == null)
    {
        throw new ArgumentNullException();
    }

    _wheelMotor = _backWheelJoint.motor;      
}

protected virtual void Update()
{
    // _movementInput = Input.GetAxis("Horizontal");

    if (Input.GetMouseButton(0))
    {
        _deltaMovement = Input.mousePosition.x;
        GetTouch(_deltaMovement);

        SetVelocity();

       SetWheelsMotorSpeed();
    }
}

/// <summary>
/// Get touch/mouseclick position to determine speed
/// </summary>
/// <param name="touchPos">touch/mouseclick position</param>
protected void GetTouch(float touchPos)
{
    if (touchPos > _centerScreenX)
    {
        _movementInput = touchPos - _centerScreenX;
    }
    if (touchPos < _centerScreenX)
    {
        _movementInput = _centerScreenX - touchPos;
    }
}



/// <summary>
/// Set velocity 
/// </summary>
private void SetVelocity()
{
    _physicValue = GRAVITY * Mathf.Sin((transform.eulerAngles.z * Mathf.PI) / 180f) * 80f;

    _wheelMotor.motorSpeed = Mathf.Clamp(
        _wheelMotor.motorSpeed - ( _movementInput - _physicValue) * Time.deltaTime,
        -7000f,
        7000f);
}

/// <summary>
/// Set wheels motor speed
/// </summary>
private void SetWheelsMotorSpeed()
{
    _frontWheelJoint.motor = _backWheelJoint.motor = _wheelMotor;
    }
}
0 Answers
Related